React Redux state change

2020-02-02 01:12发布

问题:

this.props.authState stays the same although I'm dispatching an action in my componentDidMount function:

componentDidMount() {
      if (localStorage.getItem('token')) {
        dispatch(updateAuthState('AUTHENTICATED'));
      }
  }

render() {
 <div>{this.props.authState}</div>
}

Home.propTypes = {
    authState: PropTypes.string
};

const mapStateToProps = (state) => {
    return {
        authState: state.authState
    }
};

const mapDispatchToProps = (dispatch) => {
  return {

  }
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);

the output is NO_AUTH (the initial value of authState)

Reducer:

export function authState(state = "NO_AUTH", action) {
    switch (action.type) {
        case 'AUTH_STATE':
            return action.authState;
        default:
            return state;
    }
}

any idea why?

回答1:

You're currently dispatching directly inside the componentDidMount which isn't mapped into:

connect(mapStateToProps, mapDispatchToProps)(Home);

This should do the job:

componentDidMount() {
      if (localStorage.getItem('token')) {
        this.props.onUpdateAuthState('AUTHENTICATED');
      }
  }

const mapDispatchToProps = (dispatch) => {
  return {
    onUpdateAuthState: function(authState) {
      dispatch(updateAuthState(authState));
    }
  }
};

Now, this will get the authState:

const mapStateToProps = (state) => {
    return {
        authState: state.authState
    }
};


回答2:

If you’re mutating the state then component will not be re rendered. You need to return {...state, authState} from your reducer. And you verify your updated state in

componentWillReceiveProps(nextProps)
  {
   }

I hope this would solve the issue.