我正在尝试清除组件state,但找不到es6语法的引用。我使用的是:
this.replaceState(this.getInitialState());
但是,这不适用于es6类语法。
我怎样才能达到同样的效果呢?
发布于 2016-01-18 09:25:29
据我所知,React组件不会保留初始状态的副本,所以您只能自己做。
const initialState = {
/* etc */
};
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = initialState;
}
reset() {
this.setState(initialState);
}
/* etc */
}注意,this.state = initialState;这一行要求你永远不要改变你的状态,否则你会污染initialState并使重置变得不可能。如果无法避免突变,则需要在构造函数中创建initialState的副本。(或者按照getInitialState()的要求,使initialState成为函数。)
最后,我建议您使用setState()而不是replaceState()。
发布于 2017-05-13 08:01:14
这是作为函数实现的解决方案:
Class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = this.getInitialState();
}
getInitialState = () => ({
/* state props */
})
resetState = () => {
this.setState(this.getInitialState());
}
}发布于 2017-11-26 06:04:23
直接设置this.state的解决方案在React 16中对我不起作用,所以下面是我重置每个键的方法:
const initialState = { example: 'example' }
...
constructor() {
super()
this.state = initialState
}
...
reset() {
const keys = Object.keys(this.state)
const stateReset = keys.reduce((acc, v) => ({ ...acc, [v]: undefined }), {})
this.setState({ ...stateReset, ...initialState })
}https://stackoverflow.com/questions/34845650
复制相似问题