当我将它与 onClick 中的其他功能一起使用时,useState 不起作用

useState doesn't work when I use it with other function in onClick

我创建了这个状态:

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>

我也不知道为什么

NEVER mutate this.state directly, as calling setState() afterward may replace the mutation you made. Treat this.state as if it were immutable.

使用传播操作:

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

你的情况:

insert([...list,'c'])