【问题标题】:Reactjs how to initialize array object in stateReactjs如何在状态中初始化数组对象
【发布时间】:2019-01-28 07:38:32
【问题描述】:

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

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

所以我将 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
  });
});

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

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

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

【问题讨论】:

  • 使用数组中的push方法将值放入数组中,有点像这样。 this.state.Weather5days.push(newArr);
  • @JohnWick 如果我直接推送到 Weather5days,这将直接改变我所知道的 reactjs 中应该避免的状态
  • 您可以像这样this.setState({ Weather5days: [...this.state.Weather5days, newArr] }) 或这样更新您的状态:this.setState({ Weather5days: this.state.Weather5days.concat([newArr]) })

标签: javascript arrays reactjs react-native


【解决方案1】:

您好,您将 Weather5days 定义为空数组并将 newArr 添加到其中,但您应该获取数组的先前状态并将您的 newArr 添加到这样的状态

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

【讨论】:

    【解决方案2】:

    当您将array 设置为状态时,您需要在callback 中验证其更新状态。因为反应中的状态行为是异步的。

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

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

    【讨论】:

      【解决方案3】:

      希望这可行。请检查

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

      【讨论】:

      • 不走运 :( 目前没有初始化 Weather5days:[{},{},{},{},{}] ..继续返回空数组
      【解决方案4】:

      你可以这样做

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

      【讨论】:

      • 不走运 :( 目前没有初始化 Weather5days:[{},{},{},{},{}] ..继续返回空数组
      猜你喜欢
      • 2019-06-22
      • 2019-01-25
      • 2021-12-31
      • 1970-01-01
      • 2019-10-26
      • 2015-05-10
      • 2020-04-21
      • 2016-03-11
      • 1970-01-01
      相关资源
      最近更新 更多