我使用react和redux。我想用mapDispatchToProps存储windowWidth,并通过props读出另一个组件中的值。不幸的是,componentWillReceiveProps永远不会获得最新的值,而是之前的值。有什么问题?
React,redux
容器:
that.props.selectWidth({windowWidth: windowWidth});
成分:
componentWillReceiveProps: function () {
const windowWidth= that.props.selectedWidth.windowWidth;
}
答案 0 :(得分:4)
componentWillReceiveProps: function () {
const windowWidth= that.props.selectedWidth.windowWidth;
}
应该是
componentWillReceiveProps: function (nextProps) {
const windowWidth= nextProps.selectedWidth.windowWidth;
}
https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops
在更新发生之前,在componentWillReceiveProps
函数this.props
的运行时仍然是当前的道具。因此,您需要使用可以传递到nextProps
的{{1}}参数,以便在组件完成更新后获取道具。