【问题标题】:ComponentDidUpdate and prevStateComponentDidUpdate 和 prevState
【发布时间】:2019-04-27 22:02:19
【问题描述】:

这是场景。我有一个父组件,一个子组件。 父组件执行 ajax 调用并将数据下推给子组件。

当子组件接收到新数据时,在(子组件的)componentDidUpdate 中,我将重新设置其内部状态。

componentDidUpdate(prevProps, prevState) { 

    if ( prevProps.myRow !== this.props.myRow ) { //check for when new data is passed into this component from its parent / container...
            this.setState({
                editableRowObj    : this.props.myRow    //... only then I should bother updating the state with the new data passed in.         
            })
    }
}

我想不出我需要在 componentDidUpdate(孩子的)内部检查的场景

prevState !== this.state

这是因为当我将新数据传递给子组件时,this.state 将等于 prevState(这将是旧状态,在接收新数据之前);即在我运行上述 setState 之前,prev 和 current 状态将保持不变。

因此我的问题是,在什么情况下我需要检查 prevState != this.state ?

【问题讨论】:

    标签: reactjs react-lifecycle react-state


    【解决方案1】:

    适用于道具的相同场景,也可以适用于道具。可能会发生这样的情况,即在状态更改时,您需要触发 API 调用来获取数据。现在您可能决定在setState 回调中调用一个函数,但是如果从多个位置更改相同的状态,那么componentDidUpdate 是一个好地方。

    【讨论】:

    • 我想在某些情况下 prevState 会很有用..我可能想多了这个问题。我在某处读到 ComponentDidUpdate 是 componentWillReceiveProps 的替代品。你能回忆一下或确认这是否正确吗?
    • componentDidUpdate 不是 componentWillReceiveProps 的替代品,它只是应该用于 componentWillRecieveProps 功能的一部分。即处理副作用。为了根据 props 的变化更新状态,你可以在 render 中使用 getDerivedStateFromProps 或 memoization。
    • 刚找到我从哪里读到的,React docs on this link reactjs.org/blog/2018/03/27/…,它说推荐的升级路径是将数据更新移动到 componentDidUpdate(和?)getDerivedStateFromProps。这可能就是你所说的,但我必须研究那个例子
    【解决方案2】:

    按原样比较状态没有意义,因为它们永远不会相同。您以这种方式比较的是对状态的引用,而不是嵌套值。此外,您应该小心使用这个函数,并且在 componentDidUpdate 中使用 setState 被认为是一种反模式并且不可取 - 甚至还有一个 ESlint rule 强制不这样做。

    比较状态(或道具)的一个场景是在函数shouldComponentUpdate(nextProps, nextState) 中,您可以在其中决定组件是否应该更新(返回布尔值)。

    【讨论】:

    • There's no meaning in comparing the states as is, as they will never be the same 不是真的,child 中的 componentDidUpdate 可以被调用,因为 child 本身的 prop 更新或 state 更新
    • 状态(prevState 和 this.state)与我描述的场景完全相同。这就是我问这个问题的原因。但感谢您的回答。无论如何,我在某处读到 ComponentDidUpdate 是 componentWillReceiveProps 的替代品。
    猜你喜欢
    • 2019-11-12
    • 2018-06-11
    • 2022-11-17
    • 2020-11-10
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-16
    • 2016-10-19
    相关资源
    最近更新 更多