React替换组件WillReceiveProps



在我的子组件中具有以下方法,该方法更新道具更改的状态,可以很好地进行

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
});
}
}

您设置状态,这将触发另一个调用,更新将再次调用,依此类推。您必须先检查该值是否正在更改,然后设置状态。

componentDidUpdate(nextProps) {
console.log(nextProps);
if (nextProps.fields !== this.state.nextProps.fields){
this.setState({
fields: nextProps.fields,
containerClass: nextProps.containerClass
});
}
}

我建议你用钩子看这里。

我以前去过那里很多次。。你所需要做的就是将this.setState({..封装在一些法典中。

您有componentDidUpdate(prevProps, prevState, snapshot),所以只需比较nextProps.fields和/或nextProps.containerClass是否与this.props.fieldsthis.props.containerClass不同,然后再设置State

Btw,在CDM中nextProps实际上是prevProps

相关内容

  • 没有找到相关文章

最新更新