无法在本机反应中获取数据数组

时间:2018-10-09 06:47:52

标签: json api react-native get fetch-api

我正在为我的应用程序使用react native CRNA,但无法从API加载数据数组。

这是我的代码:

constructor(props){
    super(props);
    this.state ={
        branches: [],
        loading: false,
    }
}


componentDidMount() {
    fetch('APIurl', {
            method: 'GET',
        })
      .then((response) => response.json())
      .then((responseJson) => {
          this.setState({
          branches: responseJson.data,
          loading: true,
          })
          console.log(responseJson);
          return responseJson;
      })
        .catch(error=>{
            console.log(error);
        });
    }
}
  render(){
    return(
       <Text style={{margin: 2, alignItems: 'stretch', 
                 flex:1, fontWeight: 'bold'}}> 
       {this.state.branches.name}</Text>
       <Text style={{margin: 2, justifyContent: 'space- 
         around', alignItems: 'stretch', flex:2,}}> 
       {this.state.branches.address}</Text>
      <Picker
       selectedValue={this.state.branches.name}
       mode="dropdown"
       style={{ height: 50, justifyContent: 'space- 
       around', flex:4, alignItems: 'stretch', }}
        onValueChange={(itemValue, itemIndex)=> 
      this.setState({branches: key})}>
        {this.state.branches.map((branches, key)=> (
        <Picker.Item label={branches.name} value={branches.name} key= 
       {branches.branch_id}/>)
        )}
     </Picker>
      <View style={{flex: 5, flexDirection:'column', alignItems: 'stretch',justifyContent: 'space-around'}}>
          <Button
            title="GO"
            titleStyle={{ fontWeight: "700" }}
            buttonStyle={{
            backgroundColor: "#5eac1a",
            width: 250,
            height: 45,
            borderColor: "transparent",
            borderWidth: 0,
            borderRadius: 25
            }}
           />);
         }
     }

我尝试运行该代码时未显示任何错误。但是它什么也没显示,就像无法从API获取任何数据一样。谁能帮帮我吗?非常感谢。.

编辑:它不显示任何错误,而是警告。

  

数组或迭代器中的每个子代都应具有唯一的“键”属性。

1 个答案:

答案 0 :(得分:0)

在responsejson内部,您可以执行以下操作。

responsejson.forEach((item)=>{

this.state.branches.push({
 branchid:item.branch_id

})


})
  • 此branch_id来自json数据类型。
相关问题