Javascript 为什么我的状态在我的组件中似乎没有更新?

Javascript 为什么我的状态在我的组件中似乎没有更新?,javascript,reactjs,redux,Javascript,Reactjs,Redux,我是新来Redux的,虽然我以前在React上做过一些工作 我正在使用a测试在我的应用程序中使用动作、动作创建者和还原器,到目前为止,我认为我已经完成了90%的测试 componentDidMount() { this.props.levelUp(); this.props.levelUp(); this.props.levelUp(); this.props.levelUp(); this.props.levelUp(); console.l

我是新来Redux的,虽然我以前在React上做过一些工作

我正在使用a测试在我的应用程序中使用动作、动作创建者和还原器,到目前为止,我认为我已经完成了90%的测试

  componentDidMount() {
    this.props.levelUp();
    this.props.levelUp();
    this.props.levelUp();
    this.props.levelUp();
    this.props.levelUp();
    console.log("final prop");
    console.log(this.props);
  }

const mapStateToProps = (state) => {
  console.log("state general");
  console.log(state.general);
  return {
    general: state.general,
  };
};
这两个控制台日志在这里都会被触发,它们会随着每一个级别的上升操作而增加,或者随着每一个级别的下降操作而减少

function mapDispatchToProps(dispatch) {
  return bindActionCreators(generalActions, dispatch);
}
这在我的reducer文件中:

export default (state = 1, action) => {
  console.log(state);
    switch (action.type) {
      case 'LEVEL_UP':
      console.log(action.type);
        return state + 1;
      case 'LEVEL_DOWN':
          return state - 1;
    }
    return state;
  };
这里我的控制台日志似乎捕捉到了正确的增量-每次我调用这个.props.levelUp()时,减速机中的值都会增加一个

但是,当我在
componentDidMount()
中最后记录道具时,值为1


为什么会这样?我不是一直保存数据吗?我没有按照预想的方式返回状态还有其他原因吗?

componentDidMount
一旦该组件装载,就会触发。之后,您的操作被触发,因此您应该在
componentdiddupdate()
static getDerivedStateFromProps()中执行
console.log()
语句

有关react中生命周期的更多信息:


问候

是的,就是这样。非常感谢你。我将阅读更多关于生命周期的文章。