0

I have a component Parent, which render a big form. Parent-component has presentational child components Child1 - Child4, which render inputs.

When Parent.props are changing, values of Child1 - Child4 should be dropped to default from props. A user has to have an ability to change ChildN value by parent method.

I need something like componentWillReceiveProps, to calculate new Parent.state depending on Parent.props when it changes only.

I can't use getDerivedStateFromProps, because I need access to old props and new either. getDerivedStateFromProps give access to new props only. I don't want to use componentWillReceiveProps.

class Parent extends Component {
state = {
    value: Object.assign({}, this.props.value)
};
handleInputChange(event) {
    this.setState({
        value: event.currentTarget.value
    });
}
render() {
    return (
        <Child
            onChange={this.handleInputChange.bind(this)}
            value={this.state.value}/>

    )
}}class Child extends Component {
render() {
    return (
        <input type="text"
           name="input"
           value={this.props.value}
           onChange={this.props.onChange.bind(this)}
        />

    )
}}
Anna
  • 31
  • 1
  • 4
  • 2
    Suggest you to go thru this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#preferred-solutions – Isaac Feb 18 '19 at 12:21
  • you could use shouldComponentUpdate. – Varun Suresh Kumar Feb 18 '19 at 12:27
  • whenever some props change the component updates, and you can easily use `prevProps` and `prevState` there look at https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/postrender_with_componentdidupdate.html – Amir-Mousavi Feb 18 '19 at 12:35
  • @VarunTheFalcon `shouldComponentUpdate` is for a different purpose altogether – Agney Feb 18 '19 at 12:39

1 Answers1

0

There are two options:

shouldComponentUpdate(nextProps, nextState) {
if (this.props.value.id !== nextProps.value.id) {
    this.setState({
        value: Object.assign({}, nextProps.value)
    });
}
return true;}

Minus: component re-render twice if props changed. Another option:

shouldComponentUpdate(nextProps, nextState) {
if (this.props.value.id !== nextProps.value.id) {
    this.state.value: Object.assign({}, nextProps.value)
}
return true;}

Minus: direct mutation, but render() already called. I don't like both options(and using componentDidUpdate), they don't look like best practice.

Anna
  • 31
  • 1
  • 4
  • It breaks "Single Responsibility Principle" of a function. It should just do a boolean check but it is doing other stuff as well. What about componentDidUpdate(..) ? – Oliver Watkins Jun 18 '19 at 09:22