0

我创建了这个状态:

const [list, insert] = React.useState(["a","b"]);

我有一个按钮,当我按下它时,我希望它设置list["a","b","c"]

有用:

<button onClick={() => insert(list.concat(["c"]))}>Insert</button>

但它没有:

<button onClick={() => {list.push("c");insert(list)}}>Insert</button>

我不知道为什么

4

1 回答 1

1

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

使用传播操作:

this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array

在你的情况下:

insert([...list,'c'])
于 2020-04-08T03:05:08.463 回答