首页 > 解决方案 > 当我将它与 onClick 中的其他功能一起使用时,useState 不起作用

问题描述

我创建了这个状态:

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>

我不知道为什么

标签: javascriptreactjsuse-state

解决方案


永远不要直接改变 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'])

推荐阅读