React Redux state change

后端 未结 2 1016
生来不讨喜
生来不讨喜 2020-12-06 22:52

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

componentDidMount() {
            


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 23:49

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

提交回复
热议问题