使用 setState 推入数组 - React Native

问题描述

我是 React Native 的新手,我正在使用来自不同 url 的 api 处理一个项目。当我使用 fetch 到 url 时,我想用 setState 设置我的状态,但是当我尝试它时,console.warn 显示我的数组 empy。我的代码有什么问题?我感谢任何反馈:)

  constructor() {
    super();

    this.state = {

      location: [],current: [],condition: [],cities: ["london","paris","hongkong","buenos_aires"]
    
    }
  }

  componentDidMount() {

    let fetches = []
    this.state.cities.forEach(
      city => {
        let resp = fetch('http://api.weatherapi.com/v1/current.json?key=10eb2b8701194b128b2122427211005&q=' + city + '&aqi=no').then(res => res.json());
        fetches.push(resp)
      }
    )


    Promise.all(fetches).then(jsonList => {

      jsonList.forEach(
        json => {
          this.setState(state => {
            const location = state.location.concat(json.location)
            const current = state.current.concat(json.current)
            const condition = state.condition.concat(json.condition)

            return {
              location,current,condition,}
          })


        })
    }).catch(function (error) {

      console.error(error)
    })
    console.warn(this.state)
  }

解决方法

setState 不会立即更新状态——它会在下一次渲染时更新。假设您实际上是从 API 取回数据,那么您的 console.warn 将显示当前渲染的状态。

您可以使用回调函数(setState 的第二个参数)查看设置后的值。

您还可以通过使用阵列扩展一次性完成所有更新。

Promise.all(fetches).then(jsonList => {
  this.setState(state => {
     return {
       location: [...state.location,...jsonList.map(i => i.location)],current: [...current,...jsonList.map(i => i.current)],condition: [...state.condition,...jsonList.map(i => i.condition)],}
  },() => {
     console.log(this.state);
  });
})