简体   繁体   中英

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.

I also have a Controlled element - an HTML text Input element which is associated with the same state variable.

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.

As a React novice, I don't understand why this happens. The above action should only occur when a new prop value is received, like the name 'nextProps' suggests.

Please suggest how to get the desired behaviour:

  1. Use prop to set initial state
  2. Let my controlled element (html input tag) set next values of the state variable
  3. iff new prop value is received, assign that to the next value of the state variable

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM