【问题标题】:React Native: can't get the data but the data can be seen i using console logReact Native:无法获取数据,但使用控制台日志可以看到数据
【发布时间】:2020-05-06 11:39:53
【问题描述】:

我仍然是使用 react native 的新手,我遇到了这样的问题: 我试图从这个 api 获取数据,它是 https://covid19.mathdro.id/api 只是为了获得死亡患者的价值,但我在应用程序中什么都没有,它没有显示死亡的价值,但在控制台中它显示了价值和细节 这是我使用的代码:

class Deaths extends React.Component{
constructor(){
    super();
    this.state = {
        Dead: [
        ],
        refreshing: false
    }

}

}
renderItem = ({item}) => (
    <View>
        <Text>{item.value}</Text>
        <Text>{item.detail}</Text></View>

)


onRefresh = () => {
    this.getDataApi();

}

componentDidMount = () => {
    this.getDataApi();
}

getDataApi = async () =>{
    this.setState({ refreshing: true})
    const response = await fetch('https://covid19.mathdro.id/api/')
    const json = await response.json();
    this.setState({Dead: json.deaths, refreshing: false})
}

render(){
    console.log(this.state.Dead)
    return(
        <View>
            <FlatList
                data={this.state.Dead}
                keyExtractor={item => item.deaths.toString()}
                renderItem={this.renderItem}
                refreshing = {this.state.refreshing}
                onRefresh={this.onRefresh}
            />
        </View>
    )
}

【问题讨论】:

    标签: react-native


    【解决方案1】:

    数据没有显示,因为您需要将数组传递给 FlatList,但您传递的是一个对象,在您的情况下,您不需要 FlatList,您可以直接这样做:

    return (
        <View>
           <Text>{this.state.Dead.detail}</Text>
           <Text>{this.state.Dead.value}</Text>
        </View>
    );
    

    【讨论】:

      【解决方案2】:

      在您将状态作为extraData 传递给您的平面列表之前,平面列表不会随着状态更改而刷新

      <FlatList
        ...
        extraData={this.state}
      />
      

      您可以在文档中查看它。 https://reactnative.dev/docs/flatlist

      【讨论】:

        【解决方案3】:

        您需要将一个数组传递给FlatListdata 属性。在响应中,deaths 不是数组:

        "deaths":{"value":257818,"detail":"https://covid19.mathdro.id/api/deaths"}
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-03
          • 2020-04-10
          • 1970-01-01
          • 2021-05-19
          • 1970-01-01
          相关资源
          最近更新 更多