How do I clear the state in the WillUnmount component?

I am installing the code as shown below.

componentWillUnmount() { 
    this.setState({'modal':false}) or this.setState({})
}

      

But the state is not clear. How can i do this? I need a clear state when leaving the component.

+2


source to share


2 answers


Only the state change for the keys passed is reactive, so if you pass in an empty object, the result will not change anything. If you have a fortune

{
   first: 1,
   second: 2,
   third: 3,
}

      

call

setState({
    first: 10
})

      

will update your state to



   {
       first: 10,
       second: 2,
       third: 3,
    }

      

To clear your state, at least one way to clear it all up is to explicitly set all your keys to undefined, like

const blankState = {};
Object.keys(this.state).forEach(stateKey => {
  blankState[stateKey] = undefined;
});
this.setState(blankState);

      

More details can be found in the docs on the React website. https://facebook.github.io/react-native/docs/state.html

+1


source


According to the folks at Facebook, setState should not be called on the WillUnmount component as the component is about to be destroyed and will never be re-installed. If you just want to "clear" the state, then there is no need to do this, as any new component instance will have a clear initial state.



See here for whatever situation is spoken of.

0


source







All Articles