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

新手上路,请多包涵

我是 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),而且我不能每次都按字面意思做 [{},{}..]。初始化状态未知长度的数组对象的正确方法是什么?

原文由 Eric Ahn 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 580
2 个回答

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

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

我认为您只缺少这一点。

原文由 Manoz 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

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

原文由 user3379150 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题