2017-11-10 8 views
1

ネイティブに反応します。 APIを使用してデータベースからピッカーに値を追加したいのですがどうすればよいのでしょうか。ここでPickerの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); 
     }); 
    } 

は、私は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> 
    );}} 

答えて

1

を挿入する必要のある私のピッカーである: - ここにhttps://reactnativecode.com/create-picker-spinner-using-dynamic-json-data/

コードですスニペット: -

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); 
    }); 
} 

以下のコードは、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> 
    );}} 
関連する問題