在componentDidMount()函数中获取多个API请求是本机的

时间:2017-12-07 06:11:56

标签: android reactjs react-native picker

我想在componentDidMount()函数中获取多个API请求。我有picker从API调用中获取项目。我有另一个API返回一个选择器值。现在我想在选择器中设置选择后一个API中收到的值。我正在尝试在componentDidMount函数中获取两个API 这是我的代码。请告知我失踪的地方。

import React, { Component } from 'react';

import { AppRegistry, StyleSheet, View, Platform, Picker, ActivityIndicator, Button, Alert} from 'react-native';

export default class FirstProject extends Component {

 constructor(props)
 {

   super(props);

   this.state = { 

   isLoading: true,

   PickerValueHolder : ''

  }
 }

 componentDidMount() {

  const base64 = require('base-64');

// my  API which fetches picker items 
      return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
        .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);
        });

  // another api which fetches a particular fruit_id from database which i ave to set selected in picker.
fetch('http://my_api_url', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    "fruit_id":"123"
  })
}).then((response) => response.json())
    .then((responseJson) => {
      this.setState({
        isLoading: false,
        PickerValueHolder: responseJson,
      }, function() {
        // In this block you can do something with new state.
      });
    })
    .catch((error) => {
      console.error(error);
    });
    }

    GetPickerSelectedItemValue=()=>{

      Alert.alert(this.state.PickerValueHolder);

    }

 render() {

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

   return (

    <View style={styles.MainContainer}>

          <Picker
            selectedValue={this.state.PickerValueHolder}

            onValueChange={(itemValue, itemIndex) => this.setState({PickerValueHolder: itemValue})} >

            { this.state.dataSource.map((item, key)=>(
            <Picker.Item label={item.fruit_name} value={item.fruit_name} key={key} />)
            )}

          </Picker>

          <Button title="Click Here To Get Picker Selected Item Value" onPress={ this.GetPickerSelectedItemValue } />

    </View>

   );
 }
}

const styles = StyleSheet.create({

MainContainer :{

justifyContent: 'center',
flex:1,
margin: 10
}

});

1 个答案:

答案 0 :(得分:1)

正如您在评论中所述,您的第二个API回复:

[{"fruit_id": "123","fruit_name":"Strwaberry"}]

所以它可能会有微小的变化:

.then((responseJson) => {
  this.setState({
    isLoading: false,
    PickerValueHolder: responseJson[0].fruit_name,
  }, function() {
    // In this block you can do something with new state.
  });
})