简体   繁体   中英

How to update state when props changes

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)}
        />

    )
}}

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.

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