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还是没有更新的状态。
是我的写法有什么问题吗?还是哪里不对,求指点
你应该在componentWillReceiveProps(nextProps)这个方法里,判断nextProps.currentStep !== this.props.currentStep时,说明currentStep更新了,这时候你就可以使用nextProps.currentStep这个更新的值做你要做的逻辑了。