gpt4 book ai didi

javascript - componentWillReceiveProps 与 getDerivedStateFromProps

转载 作者:搜寻专家 更新时间:2023-11-01 04:12:41 25 4
gpt4 key购买 nike

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不是 componentWillReceiveProps 的直接替代品,纯粹是因为它在每次更新后都会被调用,无论是状态变化、 Prop 变化还是父元素的重新渲染。

无论如何,只需从 getDerivedStateFromProps 返回状态即可不是正确的方法,您需要在返回值之前比较状态和 Prop 。否则每次更新状态都会重置为 props 并且循环继续

根据 docs

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

This method exists for rare use cases where the state depends on changes in props over time. For example, it might be handy for implementing a <Transition> component that compares its previous and next children to decide which of them to animate in and out.

Deriving state leads to verbose code and makes your components difficult to think about. Make sure you’re familiar with simpler alternatives:

If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

If you want to re-compute some data only when a prop changes, use a memoization helper instead.

If you want to “reset” some state when a prop changes, consider either making a component fully controlled or fully uncontrolled
with a key instead
.

P.S. 注意 getDerivedStateFromProps 的参数是 propsstate而不是 nextPropsprevProps

要了解更多详情,

为了根据 props 的变化进行变化,我们需要将 prevPropsState 存储在状态中,以便检测变化。一个典型的实现看起来像

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;
}

关于javascript - componentWillReceiveProps 与 getDerivedStateFromProps,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671593/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com