简体   繁体   中英

Why in shouldComponentUpdate() nextProps and this.props are the same?

I have a simple React app which has two form components.

I read that by default React re-renders all components when any state changes.

To improve performance I'd like to stop from re-rendering form 2 when user changes form 1 and vice-versa.

When I return false in shouldComponentUpdate it stops rendering that component and that is right however when I add logical comparisons to figure out whether current props state is different from nextProps state it gives me always the same result.

Here is an example https://glitch.com/edit/#!/smoggy-emmental-jep3kk5ly?path=src/App.js:8:17

If you open browser console it logs current props and nextProps also indicates which component is re-rendering.

Can you tell me what should I do to stop re-rendering form 2 when the user changes inputs in form 1?

Or what I am doing incorrectly?

I searched a lot but cannot find a helpful result.

In your App.js, all the methods(may it be this.nameChange or this.typeChange) are changing the values on the same state.form object. Since it is the same instance of form object all the time, in shouldComponentUpdate of Form component this.props.form == nextProps.from is true.

If you want the props to change, instead of

let {form} = this.state;
form.type = e.target.value;
this.setState({form});

try doing

this.setState({ form: {...this.state.form, type: e.target.value} })

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