react-redux中dispatch action后获取当前组件的props为什么没有更新?

新手上路,请多包涵
class Test extends Component {

    next() {
        this.props.onNextStep()
        console.log(this.props.currentStep) //这里输出的不是最新的状态 如:next后没有更新为1,还是0
    }

    prev() {
        this.props.onPrevStep()
        console.log(this.props.currentStep) //这里输出的不是最新的状态
    }

    render() {
        return (
                <Button  onClick={() => this.next()}>下一步</Button>
                <Button  onClick={() => this.prev()}>上一步</Button>
        );
    }
}

const mapStateToProps = (state) => {
    console.log(this.props.currentStep) //这里输出的是更新后的状态 如:点击next后为1
    return {
        currentStep : state.currentStep,
    };
}

const mapDispatchToProps = (dispatch) => {
    return {
        onNextStep: ()=>{
            dispatch(nextStep())
        },
        onPrevStep: ()=>{
            dispatch(prevStep())
        }
    }
}

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

reducer中就是对下一步 上一步做currentStep 加1 减1 的更新。

代码比较简略,应该看得懂。

为什么dispatch了action后,store的状态也更新了,可next和prev这两处输出的props还是没有更新的状态。

是我的写法有什么问题吗?还是哪里不对,求指点

阅读 6.8k
2 个回答

你应该在componentWillReceiveProps(nextProps)这个方法里,判断nextProps.currentStep !== this.props.currentStep时,说明currentStep更新了,这时候你就可以使用nextProps.currentStep这个更新的值做你要做的逻辑了。

你的写法么有问题,问题在于React的渲染是异步的。如果是异步,就说明不可预测,你可以加个定时器

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题