[英]React: How to use getDerivedStateFromProps() to set component state. It interferes with controlled component that uses the same state variable
I have a component that receives a variable as a prop.我有一个接收变量作为道具的组件。 The getDerivedStateFromProps() is typical, meaning that when nextProps.someProp doesn't equal prevState.someStateVar, that prop is assigned to state variable.
getDerivedStateFromProps() 是典型的,这意味着当 nextProps.someProp 不等于 prevState.someStateVar 时,该道具被分配给状态变量。
I also have a Controlled element - an HTML text Input element which is associated with the same state variable.我还有一个 Controlled 元素 - 一个 HTML 文本输入元素,它与相同的状态变量相关联。
The problem is, when I change the state variable through the controlled element, getDerivedStateFromProps() executes and sets the value back to the prop received earlier.问题是,当我通过受控元素更改状态变量时, getDerivedStateFromProps() 执行并将值设置回之前收到的道具。
As a React novice, I don't understand why this happens.作为 React 新手,我不明白为什么会发生这种情况。 The above action should only occur when a new prop value is received, like the name 'nextProps' suggests.
上面的动作应该只在接收到一个新的 props 值时发生,就像名称“nextProps”所暗示的那样。
Please suggest how to get the desired behaviour:请建议如何获得所需的行为:
The article - "You Probably Don't Need Derived State" was true.文章 - “你可能不需要派生状态”是真的。
https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
I referred the controlled component email example.我提到了受控组件电子邮件示例。
Now, the data of all the child components is stored in the parent's state.现在,所有子组件的数据都存储在父组件的状态中。 The parent's state is passed down as a prop to the child components.
父组件的状态作为道具传递给子组件。 A method in the parent component edits the state variables.
父组件中的方法编辑状态变量。 This method is passed down to the child components as a prop.
此方法作为道具传递给子组件。
Hence, the single source of truth is established and it is stored in the parent component making its children fully controlled components.因此,建立了单一事实来源并将其存储在父组件中,使其子组件完全受控。 This is how I did it.
我就是这样做的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.