更新Redux状态不会触发componentWillReceiveProps

时间:2015-10-24 18:55:38

标签: redux

我正在尝试验证登录信息。确保登录有效后,我想要开启一条新路线。 我将state.loginReducer.login作为道具传递。处理提交事件时,将调度操作,更改全局登录状态。

在这种情况下不应该ComponentWillReceiveProps被解雇?道具改变了吗?有没有更好的方法来实现这个功能?

handleSubmit (evt) {
    const {
        dispatch,
        login
    } = this.props;

    dispatch(actions.doLogin(value.login));
}

ComponentWillReceiveProps (nextprops) {
    const {
        login
    } = this.nextProps;

    if (login != null) {
        history.pushState({}, '/account');
    }
}

function mapStateToProps (state) {
    return {
        login: state.loginReducer.login
    }
}

export default connect(mapStateToProps)(Login);

3 个答案:

答案 0 :(得分:31)

如果state.loginReducer.login发生变化,则componentWillReceiveProps会被触发。如果您认为您的reducer正在返回一个新状态,并且componentWillReceiveProps未被触发,请确保新状态是不可变的。返回传递给reducer的相同状态引用将不起作用。

来自https://github.com/reactjs/redux/blob/master/docs/Troubleshooting.md

这是错误的:

function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    // Wrong! This mutates state
    state.push({
      text: action.text,
      completed: false
    });
  case 'COMPLETE_TODO':
    // Wrong! This mutates state[action.index].
    state[action.index].completed = true;
  }

  return state;
}

这是对的:

function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    // Return a new array
    return [...state, {
      text: action.text,
      completed: false
    }];
  case 'COMPLETE_TODO':
    // Return a new array
    return [
      ...state.slice(0, action.index),
      // Copy the object before mutating
      Object.assign({}, state[action.index], {
        completed: true
      }),
      ...state.slice(action.index + 1)
    ];
  default:
    return state;
  }
}

答案 1 :(得分:11)

ComponentWillReceiveProps (nextprops)

应该是

componentWillReceiveProps (nextprops)

C应为小写。实际上,mapStateToProps会触发componentWillReceiveProps。我很有信心。

答案 2 :(得分:1)

执行以下操作:

function mapStateToProps (state) {
    return {
        login: Object.assign({}, state.loginReducer.login),
    }
}

为了确保对象返回实际上是new