我有一个登录页面,我使用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>
如果我使用'componentDidUpdate',它会再次渲染组件吗? – v1shnu
您应该检查'componentDidUpdate'或'render'中的新状态。一般意义是:在调用setState之后,状态不会更新。 –
其实我的用例是这样的:如果我的用户被发现,我重定向,如果没有,我会在我的状态设置错误消息。我确信'componentWillReceiveProps'会再次渲染。但是我想知道'componentDidUpdate' update是否会自己执行'render',或者我应该使用'forceUpdate()'或类似的东西。 – v1shnu