Guy*_*Guy 53 javascript reactjs
我试图清除组件state
但无法找到es6语法的参考.我用的是:
this.replaceState(this.getInitialState());
但这不适用于es6类语法.
我怎样才能达到同样的效果?
Dav*_*lsh 83
据我所知,React组件不保留初始状态的副本,因此您只需自己完成.
const initialState = {
/* etc */
};
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = initialState;
}
reset() {
this.setState(initialState);
}
/* etc */
}
Run Code Online (Sandbox Code Playgroud)
请注意,该行this.state = initialState;
要求您永远不要改变您的状态,否则您将污染initialState
并使重置变得不可能.如果你无法避免突变,那么你需要initialState
在构造函数中创建一个副本.(或initialState
按功能制作功能getInitialState()
.)
最后,我建议你使用setState()
而不是replaceState()
.
Rap*_*toX 44
该接受的答案:
const initialState = {
/* etc */
};
class MyComponent extends Component {
constructor(props) {
super(props)
this.state = initialState;
}
reset() {
this.setState(initialState);
}
/* etc */
}
Run Code Online (Sandbox Code Playgroud)
不幸的是不正确.
initialState
作为参考传递this.state
,所以每当你改变state
你也改变initialState
(const在这里并不重要).结果是你永远不能回去initialState
.
你必须深拷贝 initialState
到state
,那么它会工作.无论是写一个深拷贝功能都自己或者使用一些现有的模块像这样.
Eru*_*aca 26
这是作为函数实现的解决方案:
Class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = this.getInitialState();
}
getInitialState = () => {
const initialState = {
/* state props */
};
return initialState;
}
resetState = () => {
this.setState(this.getInitialState());
}
}
Run Code Online (Sandbox Code Playgroud)
Cha*_*her 14
涉及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 })
}
Run Code Online (Sandbox Code Playgroud)
首先,在使用componentWillMount()
组件生命周期中的函数时,您需要存储初始状态:
componentWillMount() {
this.initialState = this.state
}
Run Code Online (Sandbox Code Playgroud)
这将存储您的初始状态,并可用于在需要时通过调用重置状态
this.setState(this.initialState)
Run Code Online (Sandbox Code Playgroud)
const initialState = {
a: '',
b: '',
c: ''
};
class ExampleComponent extends Component {
state = { ...initialState } // use spread operator to avoid mutation
handleReset = this.handleReset.bind(this);
handleReset() {
this.setState(initialState);
}
}
Run Code Online (Sandbox Code Playgroud)
请记住,为了能够重置状态,重要的是不要更改initialState。
state = {...initialState} // GOOD
// => state points to a new obj in memory which has the values of initialState
state = initialState // BAD
// => they point to the same obj in memory
Run Code Online (Sandbox Code Playgroud)
最方便的方法是使用ES6 Spread Operator。但您也可以改用Object.assign。他们都将实现相同的目标。
state = Object.assign({}, initialState); // GOOD
state = {...initialState}; // GOOD
Run Code Online (Sandbox Code Playgroud)