首页 > 解决方案 > 如何替换这个组件WillReceiveProps?

问题描述

我有一个登录和注册组件,其中包含在不推荐使用这些方法之前不久创建的表单,我一直在环顾四周,但似乎找不到解决方案,我将如何将其重构为使用getDerivedStateFromProps

  componentWillReceiveProps(nextProps) {
    if (nextProps.auth.isAuthenticated) {
      this.props.history.push("/dashboard")
    }

    if (nextProps.errors) {
      this.setState({
        errors: nextProps.errors
      });
    }

标签: javascriptreactjs

解决方案


由于您componentWillReceiveProps用于与本地状态保持同步,props因此有两种选择:

根据 props 声明你的初始状态并使用componentDidUpdate来保证 props 的同步性

class Component extends React.Component{
    state = { foo : this.props.foo }

    componentDidUpdate(prevProps){
        if(this.props.foo !== prevProps.foo)
            this.setState({ foo : prevProps.foo })
    }
}

这实际上每次都会触发额外的渲染,如果您有一些始终等于某个道具的本地状态,则可以直接使用该道具。

用于getDerivedStateFromProps根据道具更改更新状态,但请记住,您可能不需要使用它

class Component extends React.Component{
    static getDerivedStateFromProps(props){
        return { foo : props.foo }
    }
}

推荐阅读