javascript - 如何在 React Native 中将选择器数据传递到 API

标签 javascript android reactjs react-native

我构建了一个 React Native 组件,让您可以选择多种类型的啤酒,它会呈现到带有选择器的 ListView 中。

我难以理解的问题是将该数据发送到 BreweryDb Api。我不确定从哪里开始这个半完成的组件。

import React, { Component } from 'react';
import { View, Text, Picker, StyleSheet, ListView } from 'react-native'

const ds = new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2});

export default class BeerPicker extends Component {
    constructor(props){
      super(props);

      this.state = {
        beer: [],
        beerDataSource: ds.cloneWithRows([]),
        dataSource: ds.cloneWithRows(['string1', 'string2', 'string3']), //It seems to be not needed...
        items: [
          {label: 'Choose Beer', value: 'none'}, 
          {label: 'IPA', value: 'ipa'}, 
          {label: 'Pilsner', value: 'pilsner'}, 
          {label: 'Stout', value: 'stout'}
        ],
        selectedItem: 'none'
      };

      this.addBeer = this.addBeer.bind(this);
    }

    addBeer(itemValue, itemIndex){ 
      let newBeerArray = [...this.state.beer, itemValue];
      this.setState({
        beer: newBeerArray,
        selectedItem: itemValue,
        beerDataSource: ds.cloneWithRows(newBeerArray),
      });
    }

    renderRow(data) {
      return (
        <Text>{`\u2022 ${data}`}</Text>
      );
    }

    render() {
      let items = this.state.items.map((item, index) => {
        return (<Picker.item label={item.label} value={item.value} key={index}/>);
      });

      return (
        <View>
          <Picker selectedValue={this.state.selectedItem} onValueChange = {this.addBeer}>
            {items}
          </Picker>
          <ListView
            dataSource={this.state.beerDataSource}
            renderRow={this.renderRow}/>
        </View>
      )
    }
}

const styles = StyleSheet.create({
   text: {
      fontSize: 30,
      alignSelf: 'center',
      color: 'black'
   }
});

我想使用每个选定的项目并多次循环 API 以获取有关每个选定项目的信息。

最佳答案

您可以通过多种方式实现。如果您想在用户选择新啤酒时进行 api 调用,那么以下代码可能会有所帮助:

apiData:{} 添加到初始状态

在addBeer函数中添加this.fetchBeerFromApi(itemValue);

// notice I used es7 fat arrow functions to avoid having to bind in constructor
fetchBeerFromApi = async (beerId) => {
  let response = await fetch(`${BREWERY_API_URL}/beer/${beerId}`);
  response = await response.json();

  if (response.error) {
    console.error('Error with brewery api beer request', response.error);
    return false;
  }
  const apiData = this.state.apiData;
  apiData[beerId] = response;
  // Or handle storing apiData somewhere else... I usually use immutable data
  // structures to avoid deeply nested data not triggering re-rendering issues
  // so this may or may not be problematic...
  // Here is the immutablejs alternative to those last two lines:
  // const apiData = this.state.apiData.set(beerId, response);

  // Here we store it back to state where you can handle rendering the data if
  // it is available
  this.setState({apiData});
}

关于javascript - 如何在 React Native 中将选择器数据传递到 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521889/

相关文章:

javascript - 当模态主体内的视频停止播放时自动关闭 Bootstrap 模态

javascript - 我想用 Javascript 编写桌面 OSX 或 Windows 应用程序——有什么经验吗?

javascript - 递归迭代结构

android - 错误 :(39, 13) 无法解析 : com. android.support :appcompat-v7:26. 0.0

Java服务器如何处理Client请求并响应呢?

javascript - 如何使用 javascript 或 React 检查某些标签中的某些文本在网页上是否可见?

javascript - ReactJS 如何处理 Rails 事件记录关联

javascript - 具有多个提交按钮的条件表单验证

javascript - ReactJs动态html,将值绑定(bind)到子类

android - 在 FlutterSplashView.java 为我发布的一个应用程序获取 ClasscastException