Eri*_*Ahn 5 javascript arrays reactjs react-native
我是 reactjs 的新手,我正在学习在 reactjs 中更改状态。我正在尝试以未知长度的状态初始化数组对象,然后使用设置状态更新数组对象。以下是代码:
state = {
error: null,
temperature: null,
isLoaded: false,
Weather5days: [],
};
Run Code Online (Sandbox Code Playgroud)
所以我将 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
});
});
Run Code Online (Sandbox Code Playgroud)
现在上面的代码没有错误,但是当我调用 console.log(this.state.Weather5days) 时,数组是空的。所以我认为初始化 Weather5days 的方式是错误的,所以我尝试了以下方法:
state = {
error: null,
temperature: null,
isLoaded: false,
Weather5days: [{}, {}, {}, {}, {}], //array object of length 5
};
Run Code Online (Sandbox Code Playgroud)
它有效。这是解决方案的一半,因为在某些情况下,您不知道数组的长度(来自 API),而且我不能每次都按字面意思执行 [{},{}..]。初始化状态未知长度的数组对象的正确方法是什么?
Man*_*noz -1
当您设置array状态时,您需要在 中验证其更新状态callback。因为 React 中的状态行为是异步的。
this.setState({
Weather5days: newArr //set state of the weather5days
},()=> {
console.log(this.state.Weather5days);
});
Run Code Online (Sandbox Code Playgroud)
我认为你只忽略了这一点。
| 归档时间: |
|
| 查看次数: |
20937 次 |
| 最近记录: |