Har*_*anu 4 javascript functional-programming ecmascript-6 reactjs
我在一个模态中渲染一个数组.一旦模态关闭,我需要清空数组.以下代码更新数组但不点击closeModal时不清除数组.
constructor(props,context) {
super(props,context);
this.state = {
myArray: []
};
}
pushData(newVar) {
this.setState((state) => {
myArray: state.myArray.push(newVar)
});
}
closeModal() {
this.setState({
myArray: []
})
}
Run Code Online (Sandbox Code Playgroud)
Har*_*anu 10
我发现问题是我的closeModal在关闭模态时根本没有被调用.我这样做是为了关闭componentWillUnmount函数的closeModal.我明白以下代码会导致问题.
this.state.myArray=[]
Run Code Online (Sandbox Code Playgroud)
我把它改回来了
this.setState({myArray: []});
Run Code Online (Sandbox Code Playgroud)
您也可以使用它来清除数组而不使用 setState:
this.state.your_array.length = 0;
Run Code Online (Sandbox Code Playgroud)
这适用于任何函数。
更新 功能组件:
setYourArray([])
Run Code Online (Sandbox Code Playgroud)