javascript - React,过滤器功能中的c是什么
问题描述
我有来自教程的以下代码
handleDelete = counterId => {
const counters = this.state.counters.filter(c => c.id !== counterId);
this.setState({ counters });
};
我正在创建一个新常量,其中包含删除了 counterId 的现有数组。
但我不明白“c”在做什么,“c.id”来自哪里?
为什么不是我绑定到函数的属性“counterId”。
谢谢
解决方案
它不是 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));
推荐阅读
- angular - Angular 7:从订阅内部调用 ChangeDetectorRef detectChanges() 会导致无限循环
- rendering - SceneKit 中带有反射的透明玻璃
- angular - Angular Can't access _body with custom error Message from HttpErrorResponse from .net core webapi
- docker - 无法(退出状态 66)在基于 Windows 的 Docker 容器中下载 Golang 包
- angular - URL段更改后如何重新加载路由子组件?
- c++ - 如何计算输入的字符数?
- java - 使用 RabbitMQ Web STOMP 插件的 Spring Boot 连接失败
- java - org.krysalis.barcode4j.BarcodeException: No barcode configuration element not found
- node.js - 通过 http 的 Pushpin Web-Sockets
- react-native - onPress 不适用于 TouchableWithoutFeedback