【问题标题】:componentWillReceiveProps vs getDerivedStateFromPropscomponentWillReceiveProps 与 getDerivedStateFromProps
【发布时间】:2018-08-03 11:26:08
【问题描述】:

componentWillReceiveProps 和 getDerivedStateFromProps 到底是什么对我来说是个微妙的问题。因为,我在使用 getDerivedStateFromProps 时遇到了一个问题:

// Component 
state = {
  myState: []
}

// Using this method works fine:

componentWillReceiveProps(nextProps) {
  this.setState({
    myState: nextProps.myPropsState
  })
}

// But using this method will cause the checkboxes to be readonly:

static getDerivedStateFromProps(nextProps,prevProps) {
  const { myPropsState: myState } = nextProps
  return {
    myState
  }
}

// And here's checkbox
<input type="checkbox" id={`someid`} 
 onChange={(e) => this.handleMethod(e, comp.myState)} 
 checked={myState.indexOf(comp.myState) > -1} />

React 版本:16.4.1

【问题讨论】:

  • 传递给getDerivedStateFromProps ()的参数是当前的props和state,而不是nextProps和prevProps。它应该根据当前状态和道具返回下一个状态。请至少仔细阅读文档。
  • 这里不重要,参数名称可以是我们希望的任何名称,但我只是写了比较会收到道具。此外,我在这里解释为什么当我使用派生状态时复选框是只读的?
  • 如何通过将参数命名为它们不代表的东西来比较它们?还有unconditionally updating state from props is considered an anti-pattern.

标签: javascript reactjs lifecycle


【解决方案1】:

getDerivedStateFromProps 不是componentWillReceiveProps 的直接替代品,纯粹是因为它在每次更新后调用,无论是状态变化还是道具变化或父级重新渲染。

不管怎样,简单地从getDerivedStateFromProps返回状态不是正确的方法,你需要在返回值之前比较状态和道具。否则,每次更新时,状态都会重置为道具并且循环继续

根据docs

getDerivedStateFromProps 在调用渲染之前被调用 方法,无论是在初始挂载时还是在后续更新时。它应该 返回一个对象以更新状态,或null 不更新任何内容。

此方法适用于状态依赖的罕见用例 道具随时间的变化。例如,它可能对 实现一个&lt;Transition&gt; 组件,该组件比较其先前和 下一个孩子来决定他们中的哪个动画进出。

派生状态会导致冗长的代码并使您的组件 难以思考。确保您熟悉更简单的 替代品:

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

如果您想仅在道具更改时重新计算某些数据,请使用 一个 memoization 助手代替。

如果您想在道具更改时“重置”某些状态,请考虑 要么制作一个组件fully controlled要么fully uncontrolled with a key instead。

P.S.请注意,getDerivedStateFromProps 的参数是 props 和 state 而不是 nextProps 和 prevProps

要了解更多细节,

为了根据 props 的变化进行变化,我们需要将 prevPropsState 存储在 state 中,以便检测变化。典型的实现如下所示

static getDerivedStateFromProps(props, state) {
    // Note we need to store prevPropsState to detect changes.
    if (
      props.myPropsState !== state.prevPropsState
    ) {
      return {
        prevPropsState: state.myState,
        myState: props.myPropsState
      };
    }
    return null;
  }

【讨论】:

  • 感谢您的回答。但我仍然面临同样的问题。
  • @BhojendraNepal 请阅读this official blog post 了解如何处理此类情况。使用getDerivedStateFromProps 可能根本不是解决您问题的正确选择。
  • @BhojendraNepal,如果 myState 是一个数组,那么直接检查props.myPropsState !== state.prevPropsState 会失败,你要么需要深入比较数组,要么使用不可变列表
  • @ShubhamKhatri 使用从父级传递的新key(或id,如果重新初始化组件的成本很高),则应使用从父级传递的状态,以允许通过以下方式从父级重置状态传递新道具。这都被描述为here。 在每次渲染之前深入比较对象对我来说似乎不是一个好的解决方案。
  • @trixn 处理这种情况的最佳方法是记忆和使用不可变的对象列表。当我晚上有更多时间时,我会用更多细节更新答案
【解决方案2】:

最后,我解决了我的问题。这是一个痛苦的调试:

// Child Component

// instead of this
// this.props.onMyDisptach([...myPropsState])

// dispatching true value since myPropsState contains only numbers
this.props.onMyDispatch([...myPropsState, true])

这是因为,我有两个条件:1)复选框更改(组件)2)按下重置按钮(子组件)

按下重置按钮时,我需要重置状态。因此,在将状态分配给重置按钮的道具时,我使用了一个布尔值来知道它是重置后的变化。你可以使用任何你喜欢的东西,但需要跟踪它。

现在,在组件这里,我在调试控制台输出后发现了一些关于 componentWillReceiveProps 和 getDerivedStateFromProps 之间差异的提示。

// Component
static getDerivedStateFromProps(props, state) {
    const { myPropsState: myState } = props
    // if reset button is pressed
    const true_myState = myState.some(id=>id===true)
    // need to remove true value in the store
    const filtered_myState = myState.filter(id=>id!==true)
    if(true_myState) {
      // we need to dispatch the changes to apply on its child component
      // before we return the correct state
      props.onMyDispatch([...filtered_myState])
      return {
        myState: filtered_myState
      }
    }
    // obviously, we need to return null if no condition matches
    return null
  }

这是我发现控制台输出的结果:

  • 只要 props 发生变化,getDerivedStateFromProps 就会立即记录

  • componentWillReceiveProps 仅在子级传播 props 更改后记录

  • getDerivedStateFromProps 不响应 props 更改(我是指示例代码中的调度更改)

  • componentWillReceiveProps 响应 props 变化

  • 因此,我们需要在使用 getDerivedStateFromProps 时将更改提供给子组件。

在我需要的状态中粘贴真实值的过程,因为 getDerivedStateFromProps 处理所有更改,而 componentWillReceiveProps 只处理子组件将更改分派到道具。

顺便说一句,您可以使用自定义属性来检查它是否已更改,如果 getDerivedStateFromProps 则更新值,但由于某种原因,我必须调整此技术。

我的措辞可能有些混乱,但我希望你能明白。

【讨论】:

  • 列表中的元素通常应该属于同一类型。您还可以遍历整个列表以找到该值。请注意,您在每次渲染时都这样做,而在大约 99% 的情况下,内部没有 boolean。为什么不将另一个道具与您检查是否更改的重置一起传递?例如。像反应博客文章中建议的自动递增计数器?这将更有效、更容易且不易出错。您写道“getDerivedStateFromProps 不响应道具更改”。这不是真的。它响应道具或状态的每一次变化。
  • 啊,这对其他人来说有点混乱。我想说的是,使用 componentWillReceiveProps 不需要调度,但使用派生需要我调度更改。我同意你的建议,但出于某种原因,我使用了上述方法。
【解决方案3】:

来自反应文档:

请注意,无论原因如何,每次渲染都会触发此方法。这与 UNSAFE_componentWillReceiveProps 形成对比,后者仅在父级导致重新渲染时触发,而不是作为本地 setState 的结果。

每次调用setState() 后,您都有效地使用当前道具覆盖您的状态。因此,当您选中一个框 (e) =&gt; this.handleMethod(e, comp.myState) 时,假设调用 setState() 来更新复选框的选中状态。但在那之后getDerivedStateFromProps() 将被调用(渲染前)恢复该更改。这就是为什么unconditionally updating state from props is considered an anti-pattern。

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 2020-02-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多