javascript - 当我将它与 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>
我不知道为什么
解决方案
永远不要直接改变 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'])
推荐阅读
- mongodb - 排序和过滤时查询慢
- laravel - Laravel 中的表单不发送数据
- dart - Flutter:将数据从 TabBarView(StatefullWidgets)发送回主 Scaffold
- magento - 如何将名称添加到 Magento 1 时事通讯
- java - 使用 threadfactory 为线程自定义命名
- wpf - 在 WPF 中添加到 UniformGrid 的子级顺序
- javascript - 如何检查是否与服务人员脱机?
- java - 连接到 MS SQL 服务器时失败
- python - AssertionError:无法将 DjangoModelPermissionsOrAnonReadOnly 应用于未设置 `.queryset` 或具有 `.get_queryset()` 方法的视图
- c++ - 如何计算摘要/将使用哪种算法?