Reactjs getDerivedStateFromProps不';I don’我没有按预期工作

Reactjs getDerivedStateFromProps不';I don’我没有按预期工作,reactjs,Reactjs,我正在重构我的react应用程序,并用getDerivedstateFromProps替换了ComponentWillReceiveProps 然后它给出一个错误,说明无法读取未定义的属性“setState” 这是我的密码 static getDerivedStateFromProps = nextProps => { const { auth, history } = nextProps; redirectIfAuthenticated(auth.isAuthen

我正在重构我的react应用程序,并用getDerivedstateFromProps替换了ComponentWillReceiveProps

然后它给出一个错误,说明
无法读取未定义的属性“setState”

这是我的密码

static getDerivedStateFromProps = nextProps => {
      const { auth, history } = nextProps;
      redirectIfAuthenticated(auth.isAuthenticated, history, './dashboard');

      if (nextProps.errors) {
         this.setState({ 
            errors: nextProps.errors 
         });
      }
   }
我在这里做错了什么?

不仅仅是对组件WillReceiveProps的重命名,而是有不同的用途和语法。它没有访问类实例的权限,因为它是静态的

另外,
getDerivedStateFromProps
应该只更新状态,没有任何副作用。所有的副作用都必须进入componentDidUpdate

static getDerivedStateFromProps(props, state) {

  if (props.errors !== state.prevErrors) {
    return { 
        errors: props.errors,
        prevErrors: props.errors
     }
  }
  return { prevErrors: props.errors}
}

render() {
    const { auth, history } = props;
    if(this.props.auth.isAuthenticated) {
        return <Redirect to={'/dashboard'} />
    };
    // extra logic here
}
静态getDerivedStateFromProps(props,state){
if(props.errors!==state.prevErrors){
返回{
错误:道具。错误,
prevErrors:props.errors
}
}
返回{prevErrors:props.errors}
}
render(){
const{auth,history}=props;
if(this.props.auth.isAuthenticated){
返回
};
//这里有额外的逻辑
}

是的,只要您使用的是react router并使用它的重定向,而不是
历史记录。按
否则在ComponentDidUpdate中执行。如果我的重定向部分是这样的,const isAuth=this.props.auth.isAuthenticated;如果(isAuth){this.props.history.push('/dashboard');}我该怎么办?你在使用react路由器吗?是的。请确认,然后您可以简单地使用
重定向
而不是历史。按我在回答中显示的方式推入渲染