React.js数据未保存到状态变量中
我正在尝试呈现我的workerData和ordersData,但是在获取API之后,可以使用地图来呈现ordersData,但是当我尝试呈现workerData时,它什么也没做。我检查了console.log,似乎它确实填充了正确的数据,但是当我尝试映射它时,它不会呈现它。我对React还是很陌生,因此可以提供任何帮助。
class FetchData extends React.Component {
constructor(props) {
super(props);
this.state = {
ordersData: [],
workersDatas: [],
};
}
componentDidMount() {
fetch("")
.then(response => response.json())
.then(data => {
this.setState({
ordersData: data.orders
}, () => {
console.log(this.state.ordersData)
this.state.ordersData.map(order => {
console.log(this.state.ordersData)
fetch(`/${order.workerId}`)
.then(result => result.json())
.then(data2 => {
this.state.workersDatas.push(data2);
})
console.log(this.state.workersDatas)
})
});
})
.catch(err => {
console.log(err)
});
}
render() {
return (
<div>
<ul>
{this.state.workersDatas.map(order => (
<li>
hello
</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render(<FetchData/>, document.getElementById('root'));
回答如下:这是因为this.setState()
可能是异步更新状态,所以不要在更新状态后立即获取状态。此document可能有助于理解状态。