首先,所有相关代码(单击文件名可查看该文件的完整源代码)。
LoginView = class extends React.Component {
handleLogin = (email, password) => {
this.props.authenticationActionCreator.login(email, password);
};
componentWillMount () {
console.log('componentWillMount', 'this.props.isAuthenticated', this.props.isAuthenticated);
}
componentWillReceiveProps () {
console.log('componentWillReceiveProps', 'this.props.isAuthenticated', this.props.isAuthenticated);
}
render () {
let {
errorMessage,
isAuthenticating
} = this.props;
return <div>
<p>this.props.isAuthenticated: {this.props.isAuthenticated ? 'true' : 'false'}</p>
<button onClick={() => {
this.handleLogin('gajus@applaudience.com', 'nosyte');
}}>Login</button>
</div>;
}
};
authentication.js
(减速器)
if (action.type === 'AUTHENTICATION.LOGIN_SUCCESS') {
return initialState.merge({
isAuthenticated: true,
token: action.data.token,
user: action.data.user
});
}
authenticationActionCreator.js
authenticationActionCreator.loginSuccess = (token) => {
let decodedToken;
// @todo Handle failure to decode token.
decodedToken = jwtDecode(token);
localStorage.setItem('token', token);
return {
type: 'AUTHENTICATION.LOGIN_SUCCESS',
data: {
token,
user: decodedToken.user
}
};
};
流程很简单:
- 用户打开页面。
- 用户单击
<button />
调用authenticationActionCreator.login
。
console.log
输出是:
componentWillMount this.props.isAuthenticated true
action AUTHENTICATION.LOGIN_REQUEST @ 16:52:50.880
componentWillReceiveProps this.props.isAuthenticated true
componentWillReceiveProps this.props.isAuthenticated false
action AUTHENTICATION.LOGIN_SUCCESS @ 16:52:51.975
预期的console.log
输出是:
componentWillMount this.props.isAuthenticated true
action AUTHENTICATION.LOGIN_REQUEST @ 16:52:50.880
componentWillReceiveProps this.props.isAuthenticated false
action AUTHENTICATION.LOGIN_SUCCESS @ 16:52:51.975
componentWillReceiveProps this.props.isAuthenticated true
问题在于render
具有正确的状态(之后的状态AUTHENTICATION.LOGIN_SUCCESS
)和componentWillReceiveProps
旧的状态(之后的状态AUTHENTICATION.LOGIN_REQUEST
)。
我是最后一次调用componentWillReceiveProps
具有与该方法相同的状态对象render
。
这是:
- 一个错误
- 我做错了什么
- 我的期望是错误的
?