清除状态es6 React [英] Clearing state es6 React
问题描述
我正在尝试清除组件 state
但找不到es6语法的引用。我正在使用:
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());
但是这不适用于es6类语法。
however this does not work with the es6 class syntax.
我如何获得相同的结果?
How would I achieve the same result?
推荐答案
到据我所知,React组件不保留初始状态的副本,因此您只需自己完成。
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 */
}
请注意行 this.state = initialState;
要求你永远不要改变你的状态,否则你将污染 initialState
并制作重置不可能。如果你无法避免突变,那么你需要在构造函数中创建 initialState
的副本。 (或者使 initialState
一个函数,按照 getInitialState()
。)
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()
.)
最后,我建议你使用 setState()
而不是 replaceState()
。
Finally, I'd recommend you use setState()
and not replaceState()
.
这篇关于清除状态es6 React的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!