Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
20
rated 0 times [  26] [ 6]  / answers: 1 / hits: 191079  / 9 Years ago, mon, january 18, 2016, 12:00:00

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?


More From » reactjs

 Answers
33

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().


[#63679] Friday, January 15, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jimmieo

Total Points: 515
Total Questions: 102
Total Answers: 110

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
;