[英]React.js/Redux - How to update state if props wasn't changed?
如果道具更改,我想更新我的本地状态。 但是我找不到适合该问题的解决方案。 getDerivedStateFromProps
仅给我nextProps和prevState,但我同时需要prevProps和nextProps。 请写出任何可能解决此问题的解决方案)
情况: Cart组件(有状态)从道具获取获取的数据,并将其放入this.state.cart
。 Cart组件具有counterHandler
方法,该方法将在每次更改计数器(onIcrease,onDecrease,onChange)时触发。 该处理程序将计算数据并根据事件生成新数据(计算totalPrice并更新商品数量)。 然后将新数据放入setState
以更新UI。 状态不会改变,因为我这样做:
static getDerivedStateFromProps(nextProps, prevState) {
if (!_.isEqual(nextProps.cart, prevState.cart)) {
return { cart: nextProps.cart };
} else return null;
}
之所以这样做,是因为我想在更改实际数据(来自props的数据)时更新状态。
目标:在不产生任何副作用的情况下更新柜台价格和总价格(这些值可能会在商店中更新或仅针对本地状态更新)。
这就是我的意思:
您可能要使用componentDidUpdate ,当组件上的道具更新时会调用它。 它接收prevProps
和prevState
作为参数,你必须获得“nextProps”为this.props
。
例如
componentDidUpdate(prevProps, prevState) {
if (!_.isEqual(this.props.cart, prevState.cart)) {
this.setState ({ cart: this.props.cart });
}
}
您可以使用react类的componentWillReceiveProps
方法。 当父组件将呈现时,将执行此方法,其子组件将在子componentWillReceiveProps
中执行componentWillReceiveProps
方法。 在孩子的这种方法中,您可以基于新道具更新状态。
componentWillReceiveProps(nextProps){
//You can access current props via this.props
//You can access newProps from argument
//Change component state after comparing both props
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.