Updating Redux state does not trigger componentWillReceiveProps

前端 未结 3 783
南笙
南笙 2020-12-29 04:41

I\'m trying to validate the login information. After making sure the login is valid I want to fire a new route. I pass the state.loginReducer.login as props. When I handle t

3条回答
  •  春和景丽
    2020-12-29 05:05

    If state.loginReducer.login changes, then componentWillReceiveProps will get triggered. If you believe your reducer is returning a new state, and componentWillReceiveProps is not being triggered, make sure that the new state is immutable. Returning the same state reference thats passed to the reducer won't work.

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

    This is wrong:

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

    This is right:

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

提交回复
热议问题