在我的子组件中有以下方法可以更新道具更改的状态,效果很好
componentWillReceiveProps(nextProps) {
// update original states
this.setState({
fields: nextProps.fields,
containerClass: nextProps.containerClass
});
}
我越来越Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code.
我尝试更新,但到目前为止没有任何成功
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.fields !== prevState.fields) {
return { fields: nextProps.fields };
}
}
componentDidUpdate(nextProps) {
console.log(nextProps);
this.setState({
fields: nextProps.fields,
containerClass: nextProps.containerClass
});
}
因为我陷入了无限循环。
如何根据新道具正确更新我的状态
你会得到循环,因为每次组件更新时你都会设置新的状态。因此,如果状态更新,则意味着组件更新,然后您再次更新它。
因此,您需要防止在状态更改时更新组件。
componentDidUpdate(prevProps, nextProps) {
if(prevProps !== this.props){
console.log(nextProps);
this.setState({
fields: nextProps.fields,
containerClass: nextProps.containerClass
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)