[英]useState doesn't work when I use it with other function in onClick
I created this state:我创建了这个 state:
const [list, insert] = React.useState(["a","b"]);
And I have a button that when I press it, I want it set list
as ["a","b","c"]
我有一个按钮,当我按下它时,我希望它设置
list
为["a","b","c"]
It works:有用:
<button onClick={() => insert(list.concat(["c"]))}>Insert</button>
But it doesn't:但它没有:
<button onClick={() => {list.push("c");insert(list)}}>Insert</button>
And I don't know why我不知道为什么
NEVER mutate this.state directly, as calling setState() afterward may replace the mutation you made.
切勿直接改变 this.state,因为之后调用 setState() 可能会替换您所做的突变。 Treat this.state as if it were immutable.
将 this.state 视为不可变。
use spread operation:使用传播操作:
this.setState({ myArray: [...this.state.myArray, 'new value'] }) //simple value
this.setState({ myArray: [...this.state.myArray, ...[1,2,3] ] }) //another array
in your case:在你的情况下:
insert([...list,'c'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.