【问题标题】:React native my app wont show any results from API GET callReact native 我的应用程序不会显示 API GET 调用的任何结果
【发布时间】:2020-08-20 02:11:44
【问题描述】:

这是我的代码 它应该可以工作,但不知何故它没有。我也尝试过使用这个 JSON https://reactnative.dev/movies.json 但我也得到了相同的结果

export default class App extends Component {
constructor() {
  super();
  this.state = {
    data: []
  }
}

componentDidmount() {
fetch('http://192.168.1.4:8080/api', {
            method: 'GET',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
        })
            .then(res => res.json())
            .then(result => {

               data = result});
}



render() {

  return (
    <View>
      <Text 
        style = {{fontSize: 18}}>
        Display API JSON DATA
    </Text>
    <FlatList
    data = { this.state.data }
    renderItem= { ({item}) =>
    <View>
    <Text>{item.title}</Text>
    <Text>{ this.state.data }</Text>
    </View>

    }
    />
    </View>
  )
}


}

这是我的 JSON 文件

 [{"price":3,"_id":"5f32d2f3f995eb0013ff4be7","title":"new book","__v":0},]

结果如下

【问题讨论】:

    标签: android reactjs react-native api


    【解决方案1】:

    使用this.setState() 设置您的组件状态。 learn more

    componentDidmount() {
    fetch('http://192.168.1.4:8080/api', {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                }
            })
                .then(res => res.json())
                .then(result => {
                       this.setState({data: result})
    });
    }
    

    【讨论】:

      【解决方案2】:

      您是否在 flatlist 之前检查过在渲染中执行 console.log 吗? this.state.data 包含什么

      【讨论】:

        猜你喜欢
        • 2020-05-05
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 1970-01-01
        • 2021-04-09
        • 1970-01-01
        相关资源
        最近更新 更多