本文介绍了反应 Redux 状态变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

this.props.authState 保持不变,尽管我在我的 componentDidMount 函数中分派了一个动作:

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

输出为NO_AUTH(authState的初始值)

the output is NO_AUTH (the initial value of authState)

减速器:

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

知道为什么吗?

推荐答案

您当前正在直接在未映射到的 componentDidMount 内部调度:

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

connect(mapStateToProps, mapDispatchToProps)(Home);

这应该可以:

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

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

现在,这将获得 authState:

Now, this will get the authState:

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

这篇关于反应 Redux 状态变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-30 01:20