2017-02-20 45 views
4

我有一个登录页面,我使用componentWillReceiveProps路由到下一页。但是我在componentWillReceiveProps内设置的state似乎没有设置。this.setState()在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)) 
     } 
    } 

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":""} 

这里甚至设置状态之后,我的状态并没有改变。

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

编辑:我有这个组件是ErrorText,它需要在errroMessage属性。

<ErrorText errorMsg={this.state.errorMessage}></ErrorText> 

回答

3

setState() is an asynchronous operation,所以它不会立即生效:

setState()入队更改组件状态并告诉阵营,这个组件及其子女需要重新渲染与更新状态[012]

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

setState()并不总是立即更新组件。它可能会批处理或推迟更新,直到稍后。这使得在拨打setState()之后立即阅读this.state是一个潜在的缺陷。取而代之的是,使用componentDidUpdatesetState回调[...],其中任一个都保证在应用更新后触发。

这里是在您的上下文setState回调的例子:

this.setState(
    { errorMessage: nextProps.authenticationError }, 
    function() { 
     console.log('this.state ::: ' + JSON.stringify(this.state)); 
    } 
); 
+0

如果我使用'componentDidUpdate',它会再次渲染组件吗? – v1shnu

+0

您应该检查'componentDidUpdate'或'render'中的新状态。一般意义是:在调用setState之后,状态不会更新。 –

+0

其实我的用例是这样的:如果我的用户被发现,我重定向,如果没有,我会在我的状态设置错误消息。我确信'componentWillReceiveProps'会再次渲染。但是我想知道'componentDidUpdate' update是否会自己执行'render',或者我应该使用'forceUpdate()'或类似的东西。 – v1shnu

0

这可能是因为this.setState是一个异步函数。您可以传递回调来处理设置状态后应该直接发生的事件。结帐this为代码示例选择了答案。

相关问题