gpt4 book ai didi

javascript - React 16.4 支持从状态更改调用 getDerivedStateFromProps。如何应对?

转载 作者:数据小太阳 更新时间:2023-10-29 04:51:55 25 4
gpt4 key购买 nike

因此 16.4“修复”了 getDerivedStateFromProps 中的一个错误,现在它会在 props 更改和状态更改时被触发。显然这是有意的,来自这篇文章:https://github.com/facebook/react/issues/12898 .但是对我来说,在状态中保存以前的 Prop 是一个主要的矫枉过正,所以我想问一下是否有人制定了处理这样的情况的程序:

class Componentche extends React.Component {
state = {
valuesForInput: {
input1: ''
}
}
static getDerivedStateFromProps(props, state) {
if (props.someInitialValuesForInput.input1 !== state.valuesForInput.input1) {
return {
valuesForInput: {
...state,
input1: props.someInitialValuesForInput.input1
}
}
}
return state;

render () {
<Input value='valuesForInput.input1' onChange='(e) => setState({valuesForInput: {...this.state, input1: e.target.value }})'
}
}

所以在上面的例子中,我永远不会改变输入,因为 getDerivedStateFromProps 将在收到的新 Prop 和 setState 触发器上执行,而且我的条件永远不会为假。

那么处理这种情况的正确方法是什么?我真的需要将旧 Prop 保留在状态中并将它们也用于条件吗?

我刚看到这个post from React但他们不提供可行的替代方案。

感谢您的帮助!

最佳答案

解决此类问题的主要思想是始终使用一个事实来源。

实际上,他们提供了 2 个推荐的解决方案,在该博客文章中根本不使用 getDerivedStateFromProps:

  1. Fully controlled component
  2. Fully uncontrolled component with a key

以及 2 个备选方案:

  1. 使用extra propgetDerivedStateFromProps
  2. 中跟踪
  3. 使用instance method结合 ref

关于javascript - React 16.4 支持从状态更改调用 getDerivedStateFromProps。如何应对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50909833/

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