Trước hết, tất cả mã có liên quan (nhấp vào tên tệp cho mã nguồn đầy đủ của tệp đó).componentWillReceiveProps trạng thái khác với trạng thái hiển thị sau khi cập nhật trạng thái redux
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('[email protected]', 'nosyte');
}}>Login</button>
</div>;
}
};
authentication.js
(giảm)
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
}
};
};
Dòng chảy rất đơn giản:
- Người dùng mở trang.
- Người dùng nhấp vào
<button />
gọi sốauthenticationActionCreator.login
.
Các console.log
đầu ra là:
Dự kiến console.log
đầu ra là:
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
Vấn đề là render
có tình trạng chính xác (tình trạng sau khi AUTHENTICATION.LOGIN_SUCCESS
) và componentWillReceiveProps
có trạng thái cũ (trạng thái sau AUTHENTICATION.LOGIN_REQUEST
).
Tôi là cuộc gọi cuối cùng tới componentWillReceiveProps
để có cùng một đối tượng trạng thái như phương thức render
.
Đây có phải là:
- một lỗi
- Tôi đang làm một cái gì đó sai
- mong đợi của tôi là sai
?
Bạn đã bao giờ tìm ra lý do tại sao? Có phải vì 'componentWillReceiveProps' được truyền với các đạo cụ cập nhật ngay cả trước khi' props' được cập nhật không? Cảm ơn bạn đã để lại câu trả lời btw. Tôi cũng không kiểm tra API trước và đã dành hàng giờ cố gắng tìm ra những gì đang diễn ra. – shriek