React Redux state change

后端 未结 2 1007
生来不讨喜
生来不讨喜 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
        }
    };
    
    0 讨论(0)
  • 2020-12-06 23:55

    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.

    0 讨论(0)
提交回复
热议问题