首页 > 解决方案 > React,过滤器功能中的c是什么

问题描述

我有来自教程的以下代码

 handleDelete = counterId => {
    const counters = this.state.counters.filter(c => c.id !== counterId); 

    this.setState({ counters });
  };

我正在创建一个新常量,其中包含删除了 counterId 的现有数组。

但我不明白“c”在做什么,“c.id”来自哪里?

为什么不是我绑定到函数的属性“counterId”。

谢谢

标签: javascript

解决方案


它不是 React JS。它是 JavaScript 的Array.prototype.filter(). 它表示计数器中的当前项目。如果函数的返回值为真,则该元素将被保留。如果没有,它将被删除。

具有相同代码的示例:

const _counters = [{
  id: 1,
  name: "Praveen"
}, {
  id: 2,
  name: "Kumar"
}];

const handleDelete = counterId => {
  const counters = _counters.filter(c => c.id !== counterId);
  return counters;
};

// Let's try deleting the Kumar.
console.log(handleDelete(2));

在上面的代码中,我用_counters它来显示一个状态变量。如果你想看看里面发生了什么,看看控制台:

const _counters = [{
  id: 1,
  name: "Praveen"
}, {
  id: 2,
  name: "Kumar"
}];

const handleDelete = counterId => {
  const counters = _counters.filter(c => {console.log(c);return c.id !== counterId});
  return counters;
};

// Let's try deleting the Kumar.
console.log(handleDelete(2));


推荐阅读