I am trying to clear a components state
but can't find a reference for the es6 syntax. I was using:
this.replaceState(this.getInitialState());
however this does not work with the es6 class syntax.
How would I achieve the same result?
To the best of my knowledge, React components don't keep a copy of the initial state, so you'll just have to do it yourself.
const initialState = {
/* etc */
};
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = initialState;
}
reset() {
this.setState(initialState);
}
/* etc */
}
Beware that the line this.state = initialState;
requires you never to mutate your state, otherwise you'll pollute initialState
and make a reset impossible. If you can't avoid mutations, then you'll need to create a copy of initialState
in the constructor. (Or make initialState
a function, as per getInitialState()
.)
Finally, I'd recommend you use setState()
and not replaceState()
.
This is the method I use. I do want to comment that
replaceState
is perfectly fine in this scenario, as it ensures that the entirety of the state object returns to a known set of values.Actually it turns out that
replaceState()
isn't even available when using ES6 classes. I've only become aware of this in the time since I posted this answer.Be aware that
setState
merges the state. If component adds fields to state that are not ininitialState
, those will not be cleared.If you're adding fields to state that weren't defined in your initial state, then you're doing it wrong.
this doesn't work properly, because if you change
state
then it also changesinitialState
because it was assigned by reference. So when you call reset it actually doesn't reset toinitialState
. Nothing changes, you have to deep copyinitialState
tostate