繁体   English   中英

应该组件更新中的突变状态反应16.6.3

[英]Mutating state in shouldComponentUpdate react 16.6.3

由于react已弃用了许多Lifecycle Methods我发现,当使用reduxconnect时,我想使用componentDidUpdate来扩展component本地状态。 问题是只有prevProps, prevState才传递给此函数。

这意味着我nextProps, nextStateshouldComponentUpdate lifeCycle`中只有nextProps, nextState nextState。

对我来说,执行以下操作本质上是错误的:

  shouldComponentUpdate(nextProps) {
    const { status_status } = nextProps;
    if(status_status === "error") {
      this.props.dispatch(resetStatus());
    }
    return true;
  }

这肯定是一个antiPattern ,我不应该这样做。

我怎样才能再拿到nextProps不使用shouldComponentUpdate

我有类似的情况,我发现getDerivedStateFromProps在这种情况下有用且合适。

static getDerivedStateFromProps(props, state) {
  // now, you may dispatch checking the condition
  // BTW, you will dispatch just using props
  // props.dispatch()
  // this.props.dispatch() // invalid
}

我从文档中知道此注释:

如果您需要根据道具的变化执行副作用(例如,数据获取或动画),请改用componentDidUpdate生命周期。

但是我只是分享我的经验,只有getDerivedStateFromProps工作的情况。

但是,我也建议您先使用componentDidUpdate挂钩。 如果一切对您都有利,那就坚持下去。 或者,如果您也面对使用componentDidUpdate并使用getDerivedStateFromProps感觉还不错,那么您可以发表自己的见解和想法作为答案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM