reactjs - this.state React 中的数组声明
问题描述
**我正在尝试创建一个包含 5 个值的数组,我可以将其与 nameArray[number] 一起使用。我认为数组的声明是错误的,但我不知道如何修复它。我的想法是:我有 5 个按钮,当我单击其中一个时,状态数组中的 5 个值中只有一个值从 false 变为 true。**
constructor(props) {
super(props);
this.state = {
activeButtons: [false, false, false, false, false]
};
}
cliccato = (e) => {
e.preventDefault();
const number = parseInt(e.target.id);
this.setState(
{
activeButtons: !this.state.activeButtons[number],
},
() => {
console.log(" "+ this.state.activeButtons[number]);
}
);
}
解决方案
您正在activeButtons
使用单个布尔值而不是更新的数组来更新您的状态。
您需要生成一个新数组并仅修改相关元素:
const newArray = [...this.state.activeButtons];
newArray[number] = !newArray[number];
this.setState({
activeButtons: newArray,
});
推荐阅读
- c# - 如何在循环 C# 中插入列表时提高性能
- arrays - 值列表上的计算字段
- javascript - 了解 http 请求如何在 Mocha 上工作
- sql-server - 获取权限错误和“功能不存在”错误
- perl - 如何在 Perl 中使用 mkdir 创建文件夹?
- c++ - 为什么我的代码在输出中添加了 93 天?
- google-cloud-platform - Google Cloud Vision - 如何检查包含上传的原始图像或处理请求结果的日志
- powershell - 通过 powershell 格式化 json
- node.js - 我们可以训练 tensorflow.js 来获取图像的某些部分吗?
- timeout - Azure 函数 host.json 超时