[英]React componentsDidUpdate vs SetState callback
如果我运行这段代码,我会在componentDidMount
陷入无限循环,在(prevState !== this.state)
中添加if语句对(prevState !== this.state)
都没有帮助。
state = {
purchaseable: false,
totalPrice: 0
}
updatePurchaseState = () => ({
purchaseable: true
});
addIngredientHandler = (type) => {
const newPrice = totalPrice + 1
this.setState({
totalPrice: newPrice
});
}
componentDidUpdate (prevProps, prevState) {
this.updatePurchaseState()
}
但是,如果我在setState
回调中执行updatePurchaseState
,则一切正常:
addIngredientHandler = () => {
let newPrice = newPrice +1
this.setState(() => ({
totalPrice: newPrice
}), () => this.updatePurchaseState());
}
根据React文档https://reactjs.org/docs/react-component.html#setstate componentDidUpdate
是执行updatePurchaseState
首选方法。
为什么componentDidUpdate
陷入无限循环,但是setState
回调如果同时更新状态并应重新呈现,则不会返回? 调用updatePurchaseState
的最佳方法是updatePurchaseState
?
每次更新组件的状态或道具时,组件将重新渲染并调用componentDidUpdate
。 因此,两个函数addIngredientHandler
和updatePurchaseState
都会触发componentDidUpdate
被调用。 在componentDidUpdate
您尝试再次调用updatePurchaseState
,从而导致无限循环。
正确执行此操作的方法是在componentDidUpdate
,您必须通过将当前状态与先前状态进行比较来检查是否应调用updatePurchaseState
:
componentDidUpdate (prevProps, prevState) {
if (this.state.purchaseable !== prevState.purchaseable) {
this.updatePurchaseState()
}
}
请阅读React的官方文档以获取更多详细信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.