更新Redux状态不会触发componentWillReceiveProps

Joã*_*ima 25 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);
Run Code Online (Sandbox Code Playgroud)

Nat*_*gen 32

如果有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;
}
Run Code Online (Sandbox Code Playgroud)

这是正确的:

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 这已经死了.在我的情况下问题是我这样做 - `return Object.assign(state,{key:newValue});` - 而不是这个 - `return Object.assign({},state,{key:newValue });`.这里的诀窍是用旧对象启动`Object.assign`来更新THAT对象,而不是返回新的东西,所以Redux似乎认为没有任何改变,即使对象的数据确实如此(因为标识符仍然是相同). (3认同)

小智 12

ComponentWillReceiveProps (nextprops)
Run Code Online (Sandbox Code Playgroud)

应该

componentWillReceiveProps (nextprops)
Run Code Online (Sandbox Code Playgroud)

C应该是小写.实际上,mapStateToProps触发器componentWillReceiveProps.我很确定.