简体   繁体   中英

React prevent change state in child component when parent component update

I have 2 component, one parent, another is child component

in my parent component I'm using react-table and inside using some component where defined react-table like

Filter: props => <FilterInnerComponent {...props} />, 

problem is in my child component I'm changing some state to true or false on click to some button. And when my data changes in my parent component. My child component too re-rendering and child component state back to default.

How to prevent this and keep the state of child component on last changes when parent component state change.

i research and see some resolution about :

shouldComponentUpdate(nextProps, nextState) {
}

but I don't know how using it. I tried this but not helped.

shouldComponentUpdate(nextProps, nextState) {
   return this.state.openTextBox != nextState.openTextBox
}

here is where i'm using my onClick function where i change my openTextBox value on my child component

changeFilterType(event) {
    if(filterType !== "All"){
        this.state.openTextBox = true
      }
      else{
        this.state.openTextBox = false
      }
 }

Please note that you are comparing this.state & nextState , rather than your this.props & nextProps . Your child's state shouldn't be changed by your parent, its props should.

You can either use react's PureComponent or shouldComponentUpdate(nextProps, nextState) .

The differences are that PureComponent performs a shallow comparison of props and state. Whereas, shouldComponentUpdate gives you more control over comparing deep props structures.

You can declare your parent component as PureComponent. If it didn't help, try using shouldComponentUpdate like so:

shouldComponentUpdate(nextProps, nextState) {
   return this.props.openTextBox != nextProps.openTextBox
}

As I can make out from your piece of code, you are using shouldComponentUpdate in the parent component.

Rather than I would say, use that in the child component. Assuming that you are only changing the boolean state value in the parent component and other data remains as it is in the logic. You can then use the object comparison method to compare between 2 props instances in the component as follows -

return this.state.openTextBox != nextState.openTextBox

If the openTextBox is just a primitve value, you can also use the Pure Component of react.

And further in onclick function you need to use something like this -

changeFilterType(event) {
 if(filterType !== "All"){
    this.setState({openTextBox: true});
  }
  else{
    this.setState({openTextBox: false});
  }
}

虽然可以在子组件中保存已更改的状态并使用它来覆盖父组件中的prop,但可以考虑让按钮触发一个事件处理程序,该事件处理程序在更高级别上更改状态,以便新值返回到子组件只是一个新的prop值。

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