React JS维护数组内部状态

h_h*_*h_h 6 javascript reactjs react-redux

我一直在使用React状态来维护一些数据.对于整数和字符串它运行良好,但遗憾的是数组不起作用.

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

constructor(props) {
    super(props);

    this.state = {
        terms: 5,
        myArray: []
    }
Run Code Online (Sandbox Code Playgroud)

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

componentDidUpdate() {
    this.state = {
        terms: this.state.terms,
        myArray: this.state.myArray
    }
Run Code Online (Sandbox Code Playgroud)

但是myArray: this.state.myArray没有用.但是terms: this.state.terms工作得很好.

有人可以帮忙!

May*_*kla 4

问题是您以错误的方式更新state值,更新状态值如下:

this.setState({
     terms: this.state.terms,
     myArray : this.state.myArray
});
Run Code Online (Sandbox Code Playgroud)

根据文档

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

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

let arr = this.state.myarr.slice();
arr.push('data');
this.setState({arr});
Run Code Online (Sandbox Code Playgroud)