Javascript 如何在 React 0.14 ES6 中点击清除状态或空数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35466287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I clear states or empty array on click in react 0.14 ES6?
提问by Harsha Kakumanu
I am rendering an array in a modal. Once the modal closes I need to empty the array.The following code updates the array but not clear array on click of closeModal.
我正在以模态渲染数组。一旦模态关闭,我需要清空数组。以下代码更新数组,但单击 closeModal 时不清除数组。
constructor(props,context) {
super(props,context);
this.state = {
myArray: []
};
}
pushData(newVar) {
this.setState((state) => {
myArray: state.myArray.push(newVar)
});
}
closeModal() {
this.setState({
myArray: []
})
}
回答by Harsha Kakumanu
I found the problem is my closeModal didnt get called at all on closing modal. I am doing that to closeModal on componentWillUnmount function. I understood that the below code causes problem.
我发现问题是我的 closeModal 在关闭模式时根本没有被调用。我这样做是为了在 componentWillUnmount 函数上 closeModal。我知道下面的代码会导致问题。
this.state.myArray=[]
I changed it back to
我把它改回
this.setState({myArray: []});
回答by dskoda1
A couple of solutions with explanations to this (albeit in ES5) can be found here:
可以在此处找到几个对此进行解释的解决方案(尽管在 ES5 中):
回答by leeCoder
You can as well use this to clear array without using setState:
您也可以使用它来清除数组而不使用 setState:
this.state.your_array.length = 0;
This will work in any function.
这将适用于任何功能。
回答by Tr4cEr
this.state.array.splice();
This will Delete or truncate whole array
这将删除或截断整个数组