【问题标题】:How do I clear states or empty array on click in react 0.14 ES6?如何在 React 0.14 ES6 中单击时清除状态或空数组?
【发布时间】:2016-05-29 17:21:12
【问题描述】:

我正在以模式渲染一个数组。一旦模态关闭,我需要清空数组。以下代码在单击 closeModal 时更新数组但不清除数组。

constructor(props,context) {
   super(props,context);
   this.state = {
      myArray: []
   };

 }

 pushData(newVar) {
   this.setState((state) => {
       myArray: state.myArray.push(newVar)
   });
 }

 closeModal() {
   this.setState({
       myArray: []
   })
 }

【问题讨论】:

  • 类似 this.state.myarray=[]
  • 嘿抱歉你是对的@Antonio this.state.myarray=[] 解决了我的问题。
  • 推送数据看起来很奇怪...我会写 this.state.myArray.push(newVar)
  • this.state.myArray.push(newVar) 这种推送方式对我不起作用。我也试过 .concat 但没用
  • state.myArray.push(newVar) 也不会按预期运行。 Array.prototype.push 返回新数组的长度,而不是其中包含新值的数组。 setState(state => ({myArray: state.myArray.concat(newVar)})) 更接近您要查找的内容。

标签: javascript reactjs functional-programming ecmascript-6


【解决方案1】:

我发现问题是我的 closeModal 在关闭模式时根本没有被调用。我这样做是为了在 componentWillUnmount 函数上关闭模式。 我知道下面的代码会导致问题。

this.state.myArray=[] // class component
const[myArray, setMyArray]=useState([]) // functional component

我改回了

this.setState({myArray: []}); // class component
setMyArray([]); // functional component

【讨论】:

  • 从不在构造函数之外赋值给this.state。这可能会解决您眼前的问题,但它导致错误。
  • 是的,请改用this.setState({ myArray: [] });
【解决方案2】:

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

   this.state.your_array.length = 0;

这适用于任何功能。

更新 功能组件:

   setYourArray([])

【讨论】:

    【解决方案3】:

    可以在此处找到一些对此进行解释的解决方案(尽管在 ES5 中):

    https://stackoverflow.com/a/29994490/4572987

    【讨论】:

    • 那么 pushData 方法正确地将 newVar 添加到状态中并导致重新渲染正确吗?为什么不让这些方法统一并让 closeModal 看起来像:this.setState((state) => { myArray: [] });
    • 如果这不起作用,我怀疑它与将实际引用 React 更改为 myArray 变量的代码有关,因此根本不会影响它..
    【解决方案4】:
    this.state.array.splice();
    

    这将删除或截断整个数组

    【讨论】:

      【解决方案5】:

      这对我有用。
      基于类的组件

      this.setState({myArray: []});
      

      使用 React Hook,

      const [myArray, setMayArray] = React.useState([]);
      setMayArray([]);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-04-17
        • 1970-01-01
        • 2019-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-18
        相关资源
        最近更新 更多