如何在点击反应0.14 ES6时清除状态或清空数组?

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)

  • _Never_ 在构造函数之外分配给 `this.state`。这可能会解决您的直接问题,但它_会_导致错误。 (2认同)

lee*_*der 5

您也可以使用它来清除数组而不使用 setState:

   this.state.your_array.length = 0;
Run Code Online (Sandbox Code Playgroud)

这适用于任何函数。

更新 功能组件:

   setYourArray([])
Run Code Online (Sandbox Code Playgroud)