我使用以下方法从保存的会话中加载数据:
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:16:46
您正在做的错误事情是尝试在您的函数上使用来自状态的值来定义您的状态。
您有两种解决此问题的方法:
1)使用setState
的回调函数,然后使用新的数据再次设置状态(在我看来,这不是最好的方法)
componentDidMount() {
if (JSON.parse(localStorage.getItem('savedData')) !== null) {
const cartItems = JSON.parse(localStorage.getItem('savedData'))
this.setState({
cartItems
}, ()=> {
this.setState({
totalPrice: this.getPriceOnLoad(cartItems),
totalItems: this.getItemsOnLoad(cartItems),
});
})
}
}
2)将值发送到您的函数
componentDidMount() {
if (JSON.parse(localStorage.getItem('savedData')) !== null) {
const savedCartItems = JSON.parse(localStorage.getItem('savedData'))
this.setState({
cartItems,
totalPrice: this.getPriceOnLoad(savedCartItems),
totalItems: this.getItemsOnLoad(savedCartItems),
});
}
}
发布于 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
复制相似问题