简体   繁体   English

使用 setState 推入 arrays - React Native

[英]Push into arrays with setState - React Native

i'm new to React Native and i was working on a project using api from different url's.我是 React Native 的新手,我正在使用来自不同 url 的 api 开展一个项目。 When i use the fetch to the url's, i want so set my state with setState but when i try it, the console.warn shows my arrays empy.当我使用对 url 的获取时,我想用 setState 设置我的 state 但是当我尝试它时,console.warn 显示我的 arrays 空。 What is the problem in my code?我的代码有什么问题? I appreciate any feedback:)我感谢任何反馈:)

  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 does not update the state immediately -- it gets updated on the next render. setState不会立即更新 state - 它会在下一次渲染时更新。 Assuming you're actually getting data back from your API, your console.warn is showing the state from the current render.假设您实际上是从 API 取回数据,您的console.warn将显示当前渲染中的 state。

You can use the callback function (second argument of setState ) to see the value after it's been set.您可以使用回调 function ( setState的第二个参数)来查看设置后的值。

You can also make all of the updates in one shot by using array spreading.您还可以通过使用数组扩展一次性完成所有更新。

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);
  });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM