【问题标题】:Mutating state in shouldComponentUpdate react 16.6.3shouldComponentUpdate 中的变异状态反应 16.6.3
【发布时间】:2018-11-26 12:50:45
【问题描述】:

由于 react 已经弃用了他们的许多 Lifecycle Methods,我发现,当我想增加 component 的本地状态时,我使用 componentDidUpdate。问题是只有prevProps, prevState 被传递给这个函数。

那意味着我在 shouldComponentUpdate lifeCycle` 中只有 nextProps, nextState

对我来说,做以下事情是天生错误的:

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

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

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

【问题讨论】:

  • 你为什么不用componentDidUpdate,它应该可以处理这样的副作用。 componentDidUpdate(prevProps) { const { status } = this.props; if(status !== prevProps.status_status && status === "error") { this.props.dispatch(resetStatus()); } }
  • ^ 恕我直言,这看起来是一个可靠的答案。
  • 啊,为什么@ShubhamKhatri 此时this.props 是当前状态
  • @JamieHutber,nextProps 将在渲染周期之后成为 currentProps,并且在状态渲染之后调用 sideEffects 比之前完美且稳定,这就是不推荐使用 componentWillReceiveProps 的原因
  • 谢谢朋友,如果你能添加这个作为答案,我会接受它。

标签: javascript reactjs redux


【解决方案1】:

我遇到过类似的情况,我发现 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
}

我从docs 知道这个注释:

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

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

不过,我也建议您先使用componentDidUpdate 挂钩。如果一切看起来对你都很好,那就坚持下去。或者,如果您也面临使用componentDidUpdate 并且使用getDerivedStateFromProps 感觉很好,那么您可以发表您的意见和想法作为答案。

【讨论】:

  • getDerivedStateFromProps 用于更新状态,所有副作用都应该进入 componentDidUpdate
  • 是的,我需要 getDerivedStateFromProps ,但没有按预期工作。只是分享我的经验。
  • 虽然你可以在 getDerivedStateFromProps 中做到这一点,但它也不适合做 React 文档中建议的事情。 ComponentDidUpdate 旨在用于此类事情。你可以阅读stackoverflow.com/questions/49599656/…
猜你喜欢
  • 1970-01-01
  • 2021-07-22
  • 2019-07-25
  • 1970-01-01
  • 2017-08-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-19
相关资源
最近更新 更多