我使用以下方法从保存的会话中加载数据:
componentDidMount() {
if (JSON.parse(localStorage.getItem('savedData')) !== null) {
this.setState({
cartItems: JSON.parse(localStorage.getItem('savedData')),
totalPrice: this.getPriceOnLoad(),
totalItems: this.getItemsOnLoad(),
});
}
}cartItems是一个对象数组。它似乎在更新之前
this.getPriceOnLoad();
this.getItemsOnLoad();函数被调用,例如,this.getPriceOnLoad函数:
getPriceOnLoad() {
let itemsPrice = 0;
for (let i = 0; i <= this.state.cartItems.length - 1; i++) {
itemsPrice += this.state.cartItems[i].quantity * this.state.cartItems[i].price;
}
return itemsPrice;
}但是,在getPriceOnLoad函数中,this.state.cartItems.length等于0,因此不执行for循环。我可以在React工具中看到这个数组有一定的长度。是因为componentDidMount()正在同步执行状态更改而不能立即看到更新的数组吗?因此,我的问题是,在数组初始化之后,我如何更新价格和数量?
发布于 2019-01-21 15:14:59
在执行getPriceOnLoad()之前执行this.setState。因此,您不能在this.state中引用getPriceOnLoad()。
调用this.setState({})时,JS首先需要为setState()函数生成对象。表示要首先运行的函数,然后是this.setState()。
而且在任何情况下,this.setState()都是一个异步函数,因此在执行setState()之后,this.state是不可直接使用的。
https://stackoverflow.com/questions/54292698
复制相似问题