在ComponentDidMount()函数中获取多个API请求



我想在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
}
});

正如您在评论中所说的,第二个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.
  });
})

相关内容

  • 没有找到相关文章

最新更新