简体   繁体   English

如何在 React State 中切换数组项

[英]How to toggle an array item in React State

Im trying to implement a simple Filter function in React.我试图在 React 中实现一个简单的过滤器功能。 I got 6 Buttons and every Button has a value.我有 6 个按钮,每个按钮都有一个值。 A button can be selected or not selected.可以选择或不选择按钮。 I just need to get the all the selected values.我只需要获取所有选定的值。 My idea was to write the value into an array when a button is clicked.我的想法是在单击按钮时将值写入数组。 When the button is clicked a second time, the item is removed from the array.第二次单击该按钮时,该项目将从数组中删除。 I tried a function which gets the array and the item to be toggled.我尝试了一个获取数组和要切换的项目的函数。 It checks if the array already has the item.它检查数组是否已经有该项目。 If yes then it uses filter to remove it.如果是,则使用过滤器将其删除。 If not it uses the spread operator to create a new array containing the values of the provided array plus the new item.如果不是,它使用扩展运算符创建一个新数组,其中包含提供的数组的值加上新项目。 My Component and the Function looks like that:我的组件和功能如下所示:

export default class App extends Component {

  constructor(props) {
    super(props);
    this.handleChangeCompetitor = this.handleChangeCompetitor.bind(this);
    this.state = {
      competitors: [],
    };
  }

  handleChangeCompetitor(filterCompetitors) {
      this.setState(state  => {
            const competitors = state.competitors.includes(filterCompetitors)
              ? competitors.filter(i => i !== filterCompetitors)//remove items
              : [ ...competitors, filterCompetitors ]; // add item
          return {
            competitors,
          };
      });
  }
}

The problem is its not working and i got this Error:问题是它不工作,我得到了这个错误:

Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

Has someone an idea why its not working or whether the approach makes any sense at all.有人知道为什么它不起作用或该方法是否有意义。

You can do:你可以做:

handleChangeCompetitor(filterCompetitors) {
  this.setState((state) => ({
    competitors: state.competitors.includes(filterCompetitors)
      ? state.competitors.filter((fc) => fc !== filterCompetitors)
      : [...state.competitors, filterCompetitors],
  }))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM