简体   繁体   English

在Picker中添加API数据值

[英]add API data values in Picker react native

I am new to react native. 我是新来的本地人。 I want to add values from database into picker using API please suggest how can i do that. 我想使用API​​将数据库中的值添加到选择器中,请建议我该怎么做。

componentDidMount() {

    return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
      .then((response) => response.json())
      .then((responseJson) => {
        let ds = new Picker.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
        this.setState({
          isLoading: false,
          dataSource: ds.cloneWithRows(responseJson),
        }, function() {
          // In this block you can do something with new state.
        });
      })
      .catch((error) => {
        console.error(error);
      });
    }

Here is my picker in which i need to insert the values that are fetched from API function componentDidMount() 这是我的选择器,我需要插入从API函数componentDidMount()获取的值

render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (

      <View style={styles.MainContainer}>
<Picker
  selectedValue={this.state.active}
  dataSource={this.state.dataSource}
  onValueChange={(activeValue, activeIndex) => this.setState({active: 
    activeValue})}>
  renderRow={(rowData) => <Picker.Item label={rowData.fruit_name} value=
   {rowData.fruit_name} />} 
    </Picker>
      </View>
    );}}

Found a solution here :- https://reactnativecode.com/create-picker-spinner-using-dynamic-json-data/ 在这里找到了解决方案: - https://reactnativecode.com/create-picker-spinner-using-dynamic-json-data/

Here is the code snippet :- 这是代码片段: -

componentDidMount() {
  const base64 = require('base-64');
return fetch('http://your_api_url', {
  method: 'POST',
  headers: {
    "Authorization": "Basic " + base64.encode("user:passwd")
  }
}).then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        dataSource: responseJson,
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
}

And below code is where we add it in a Picker. 下面的代码是我们在Picker中添加它的地方。

render() {
    if (this.state.isLoading) {
      return (
        <View style={{flex: 1, paddingTop: 20}}>
          <ActivityIndicator />
        </View>
      );
    }

    return (

      <View style={styles.MainContainer}>
<Picker style={styles.PickerStyleClass}
        selectedValue={this.state.mode}
        onValueChange={(modeValue, modeIndex) => this.setState({mode: modeValue})}>
    {this.state.dataSource.map((item, key)=>(
            <Picker.Item label={item} value={item} key={key} />)
            )}
</Picker>
      </View>
    );}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM