javascript Reactjs 如何在状态下初始化数组对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51960138/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:45:53  来源:igfitidea点击:

Reactjs how to initialize array object in state

javascriptarraysreactjsreact-native

提问by hyuk lee

I'm new to reactjs and i'm learning to change state in reactjs. I'm trying to initialize an array object in state with unknown length, and later update the array object using set state. Following is the code:

我是 reactjs 的新手,我正在学习在 reactjs 中更改状态。我正在尝试以未知长度的状态初始化数组对象,然后使用设置状态更新数组对象。以下是代码:

state = {
  error: null,
  temperature: null,
  isLoaded: false,
  Weather5days: [],
};

So I have initialized Weather5days as an array, with unknown length. I get the data for Weather5days through API as json, so after fetch, I do this:

所以我将 Weather5days 初始化为一个长度未知的数组。我通过 API 作为 json 获取 Weather5days 的数据,所以在获取之后,我这样做:

then(json => {
  var newArr = json.Forecasts.map(function(val) {
    //Forecasts have length of 5 array
    return {
      date: val.Date,
    };
  });

  console.log(newArr); // I checked, data is copied correctly in newArr.

  this.setState({
    Weather5days: newArr, //set state of the weather5days
  });
});

Now above code works with no error, but when I call console.log(this.state.Weather5days), the array is empty. So I thought the way of initializing Weather5days was wrong so I tried the following:

现在上面的代码没有错误,但是当我调用 console.log(this.state.Weather5days) 时,数组是空的。所以我认为初始化 Weather5days 的方式是错误的,所以我尝试了以下方法:

state = {
  error: null,
  temperature: null,
  isLoaded: false,
  Weather5days: [{}, {}, {}, {}, {}], //array object of length 5
};

and It works. This is half the solution because in certain circumstances, you don't know the length of the array(that comes from the API) and I cannot afford to do literally do [{},{}..] everytime. What is the proper way of initializing array object with unknown length in state?

它有效。这是解决方案的一半,因为在某些情况下,您不知道数组的长度(来自 API),而且我不能每次都按字面意思执行 [{},{}..]。初始化状态未知长度的数组对象的正确方法是什么?

采纳答案by Manoz

When you set arrayin state you need to verify its updated state in callback. Because of the behavior of states in react are asynchronous.

当您array在 state 中设置时,您需要在callback. 因为反应中状态的行为是异步的。

 this.setState({
    Weather5days: newArr  //set state of the weather5days
  },()=> {
     console.log(this.state.Weather5days); 
  });

I think you are missing this point only.

我认为你只是错过了这一点。

回答by John Wick

you can do it like this

你可以这样做

const updated = this.state.Weather5days.slice(); 
updated.push(newArr); 
this.setState({Weather5days:updated}); 

回答by Mukesh Burnwal Mike

hope this could work.please check

希望这可以工作。请检查

const {Weather5days}=this.state
              this.setState({
          Weather5days: [...Weather5days,newArr]
      });

回答by user3379150

Hi your defined the Weather5days as empty array and adding the newArr to it but you should take the previous state of array and add your newArr to the state like this

嗨,您将 Weather5days 定义为空数组并向其添加 newArr 但您应该采用数组的先前状态并将 newArr 添加到这样的状态

this.setState({
Weather5days : [...this.state.Weather5days, newArr]
})