我的要求是更新 componentWillReceiveProps 的 map 函数中的状态值。
在控制台日志中,我得到的只是 1s 但 sub.subscribed 包含 0s 和 1s
控制台窗口参考:http : //prntscr.com/jqifiz
constructor(props) {
super(props);
this.state = {
regionAll: [],
};
}
componentWillReceiveProps(nextProps){
if(nextProps.apiData !== false ){
nextProps.apiData.data.datacenter.category.map((sub)=> {
console.log(sub.subscribed,'sub.subscribed');
this.setState({
regionAll: [
...this.state.regionAll,
sub.subscribed
]
},()=>{
console.log(this.state.regionAll,'sub');
})
})
}
这是在reactjs中更新状态的正确方法吗?
setState
是 async.In Array#map
,它多次调用。只有最后一个值添加到数组 regionAll 中,而不是全部,因为具有多个值的异步 setState 调用。
您可以sub.subscribed
使用Array#reducer收集单个数组中的所有值,然后执行状态更新。
if (nextProps.apiData !== false) {
let sub = nextProps
.apiData
.data
.datacenter
.category
.reduce((accum, sub) => [
...accum,
sub.subscribed
], [])
this.setState({
regionAll: [...sub]
}, () => {
console.log(this.state.regionAll, 'sub');
})
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句