this.setState()在componentWillReceiveProps中不起作用

v1s*_*hnu 9 reactjs

我有一个登录页面,我用它componentWillReceiveProps来路由到下一页.但state我设置的内容componentWillReceiveProps似乎没有设定.

这是我的componentWillReceiveProps方法:

  componentWillReceiveProps(nextProps) {
      if (nextProps.isAuthenticated === true) {
          browserHistory.push('/home');
      } else {
        console.log("this.props :::" + JSON.stringify(this.props))
          console.log("this.state :::" + JSON.stringify(this.state))
          console.log("nextProps :::" + JSON.stringify(nextProps))
          this.setState({
              errorMessage: nextProps.authenticationError
          })
          console.log("this.state :::" + JSON.stringify(this.state))
      }
  }
Run Code Online (Sandbox Code Playgroud)

console output我得到是这样的:

this.props :::{"authenticationError":null}  
this.state :::{"username":"35135","password":"3135","errorMessage":""}  
nextProps :::{"isAuthenticated":false,"authenticationError":"Could not find user in DB."}  
this.state :::{"username":"35135","password":"3135","errorMessage":""}  
Run Code Online (Sandbox Code Playgroud)

即使在设置状态之后,我的状态也没有改变.

请告诉我,我做错了什么.

编辑:我有这个组件ErrorText,它接收errroMessage属性.

<ErrorText errorMsg={this.state.errorMessage}></ErrorText>
Run Code Online (Sandbox Code Playgroud)

keu*_*eul 10

setState()是一个异步操作,因此它不会立即生效:

setState() 排队对组件状态的更改并告诉React需要使用更新的状态重新呈现此组件及其子组件[...]

将其setState()视为请求而非立即更新组件的命令.为了获得更好的感知性能,React可能会延迟它,然后在一次通过中更新几个组件.React不保证立即应用状态更改.

setState()并不总是立即更新组件.它可以批量推迟更新或推迟更新.这使得this.state在调用setState()潜在陷阱后立即阅读.相反,使用componentDidUpdatesetState回调[...],其中任何一个都保证在应用更新后触发.

以下是setState上下文中回调的示例:

this.setState(
    { errorMessage: nextProps.authenticationError },
    function() {
        console.log( 'this.state ::: ' + JSON.stringify( this.state ) );
    }
);
Run Code Online (Sandbox Code Playgroud)