componentWillReceiveProps没有获得最新的道具

时间:2017-01-04 16:19:59

标签: reactjs redux

我使用react和redux。我想用mapDispatchToProps存储windowWidth,并通过props读出另一个组件中的值。不幸的是,componentWillReceiveProps永远不会获得最新的值,而是之前的值。有什么问题?

React,redux

容器:

that.props.selectWidth({windowWidth: windowWidth});

成分:

componentWillReceiveProps: function () {
    const windowWidth= that.props.selectedWidth.windowWidth;
 }

1 个答案:

答案 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}}参数,以便在组件完成更新后获取道具。