看不到更新状态

时间:2017-02-06 11:54:27

标签: javascript reactjs redux react-redux redux-form

我有以下行动:

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);

LoginFormredux-form组件。

因此,handleSubmit函数的输出输出是:

false
ACTION CALLED
REDUCER CALLED
true

但它给了我:

false
ACTION CALLED
REDUCER CALLED
false

但在redux dev tool我可以看到LOGIN_USER_REQUEST中的差异:

enter image description here

为什么我在handleSubmit函数中没有看到它?它与redux-form库有关吗?

额外信息:

添加了shouldComponentUpdatelogger

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;
  }

enter image description here enter image description here

1 个答案:

答案 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);
     }
}

我希望它有所帮助