我有以下行动:
export function loginUserRequest() {
console.log('ACTION CALLED');
return {
type: LOGIN_USER_REQUEST,
};
}
这是减速器:
export default function loginReducer(state = initialState, action) {
switch (action.type) {
case LOGIN_USER_REQUEST:
console.log('REDUCER CALLED');
return Object.assign({}, state, {
isAuthenticated: true,
isAuthenticating: true,
statusText: null,
});
default:
return initialState;
}
}
然后,我的组件:
class Login extends React.Component {
goHome = () => {
browserHistory.push('/');
}
handleSubmit = (values) => {
console.log(this.props.isAuthenticating);
this.props.actions.loginUserRequest();
console.log(this.props.isAuthenticating);
}
render() {
return (
<LoginForm onSubmit={this.handleSubmit} />
);
}
}
Login.propTypes = {
actions: PropTypes.objectOf(PropTypes.func).isRequired,
isAuthenticating: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
token: state.login.token,
isAuthenticated: state.login.isAuthenticated,
isAuthenticating: state.login.isAuthenticating,
});
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(actionCreators, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(Login);
LoginForm
是redux-form
组件。
因此,handleSubmit
函数的输出输出是:
false
ACTION CALLED
REDUCER CALLED
true
但它给了我:
false
ACTION CALLED
REDUCER CALLED
false
但在redux dev tool
我可以看到LOGIN_USER_REQUEST
中的差异:
为什么我在handleSubmit
函数中没有看到它?它与redux-form
库有关吗?
额外信息:
添加了shouldComponentUpdate
和logger
shouldComponentUpdate = (nextProps, nextState) => {
console.log('Should component update called');
if (this.props.isAuthenticating !== nextProps.isAuthenticating) {
console.log('distntict');
return true;
}
console.log('false');
return false;
}
答案 0 :(得分:1)
由于Javascript的异步特性,您得到了这样的结果。所以在你的代码中
handleSubmit = (values) => {
console.log(this.props.isAuthenticating);
this.props.actions.loginUserRequest();
console.log(this.props.isAuthenticating);
}
首先,您正在打印prop的值,然后调用该操作,但在操作返回具有更新状态的响应之前,将调用您的第三个语句来记录该值,因为状态尚未更新,您会看到同样的结果。
一种方法是回调,但这似乎不是你的情况的要求。如果您想记录状态,则可以在componentWillReceiveProps
函数
像
componentWillReceiveProps(nextProps) {
if(this.props.isAuthenicating != nextProps.isAuthenticating) {
console.log(nextProps.isAuthenticating);
}
}
我希望它有所帮助