首页 > 解决方案 > shouldComponentUpdate 中的变异状态反应 16.6.3

问题描述

由于 react 已弃用其中的许多内容,因此Lifecycle Methods我发现,在使用时redux以及connect当我想增加component我正在使用的 a 的本地状态时componentDidUpdate。问题只是prevProps, prevState传递给这个函数。

那意味着我只有nextProps, nextStateshouldComponentUpdatelifeCycle` 里面。

对我来说,做如下事情本质上是错误的:

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

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

那么我怎样才能在nextProps不使用的情况下获得shouldComponentUpdate

标签: javascriptreactjsredux

解决方案


我遇到了类似的情况,我发现 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那么您可以发表您的意见和想法作为答案。


推荐阅读