首页 > 解决方案 > 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]);        
      }
    );
}

标签: reactjs

解决方案


您正在activeButtons使用单个布尔值而不是更新的数组来更新您的状态。

您需要生成一个新数组并仅修改相关元素:

const newArray = [...this.state.activeButtons];
newArray[number] = !newArray[number];

this.setState({
  activeButtons: newArray,
});


推荐阅读