【问题标题】:React JS maintain array inside stateReact JS 在状态内部维护数组
【发布时间】:2024-04-20 03:25:01
【问题描述】:

我一直在使用 React 状态来维护一些数据。对于整数和字符串,它运行良好,但不幸的是数组无法运行。

在我的组件构造函数中,我有

constructor(props) {
    super(props);

    this.state = {
        terms: 5,
        myArray: []
    }

然后,我试图在 componentDidUpdate 中维护它

componentDidUpdate() {
    this.state = {
        terms: this.state.terms,
        myArray: this.state.myArray
    }

myArray: this.state.myArray 不起作用。但是terms: this.state.terms 运行良好。

有人可以帮忙吗!

【问题讨论】:

  • 为什么要在componentDidUpdate方法中设置状态??还有一件事你说不工作是什么意思,你试图更新数组?
  • 你也应该使用 this.setState() 来更新状态
  • 渲染组件后,我必须更改其他状态值。
  • @ Mayank Shukla 实际上,由于某种原因,我正在重新初始化状态,无论如何没关系。我解决了我的问题。不过感谢您及时的回复。我真的很感激。

标签: javascript reactjs react-redux


【解决方案1】:

问题是您以错误的方式更新 state 值,像这样更新状态值:

this.setState({
     terms: this.state.terms,
     myArray : this.state.myArray
});

根据DOC

永远不要直接改变 this.state,因为之后调用 setState() 可能 替换您所做的突变。将 this.state 视为 不可变。

像这样更新state array,首先使用slice()创建一个副本,然后进行更改并使用setState进行更新:

let arr = this.state.myarr.slice();
arr.push('data');
this.setState({arr});

【讨论】:

    【解决方案2】:

    你不能像这样直接设置状态,因为它是一个数组,你必须附加值或者推送值。

    试试类似的东西

    var newArray = this.state.myArray.slice();    
    newArray.push("new value");   
    this.setState({myArray:newArray})
    

    我在这里切片以使其不可变。

    【讨论】:

      【解决方案3】:

      你不能使用this.state来更新状态,你必须使用:

      this.setState(newStateObject);
      

      【讨论】: