How does react subcomponent modify props?

when a child component needs to modify the props passed by the parent component (think about this scenario),
can assign a value to its own state at initialization time

constructor (props) {
    this.state = {
        foo: props.foo
    }
}

then operate state inside the component, but if you encounter the parent component updating props, then the constructor of the child component will no longer be called, so write

componentWillReceiveProps (nextProps) {
    this.setState({ foo: nextProps.foo })
}

is it a bit troublesome to write like this, or I don"t understand the true meaning of it?

May.21,2022

  1. props is read-only
  2. you can convert in render
  3. it is wrong for you to use it this way. According to you, the state transformed by props can be changed not only by the child component, but also by the props of the parent component, which is not in line with the design principles of react.

the child component modifies the parent component's own state through the methods passed down by the parent component.


because foo is passed from the parent component, you can use props.foo directly. If you need to modify the value of foo , it is recommended that you put the method of modifying foo to the parent component, so as to avoid conflicts between child components and parent components while modifying the value of foo . Modify the passed value by passing method to reduce the coupling between parent component and child component, and also conform to React data flow specification from top to bottom

Menu