reactjs - 选择时删除数组中的 ID - 取消选择
问题描述
我正在寻找一种方法,当取消选择一行时,删除数组中的数字。
选择时 > id : [2, 7, 8]
==> 当我取消选择一项时出现问题:ID 为 8 的示例:
未选中时 > id : [2, 7, 8]
id 8 留在我的数组中。
==>当我取消选择一项并再次单击时出现问题:
id : [2, 7, 8, 8]
constructor(props) {
super(props);
this.state = {
id: [],
};
this.onRowSelect = this.onRowSelect.bind(this);
this.onSelectAll = this.onSelectAll.bind(this);
}
onRowSelect(row, isSelected, e) {
let rowStr = '';
for (const prop in row) {
rowStr += prop + ': "' + row[prop] + '"';
if (isSelected == true){
this.setState({ id: [...this.state.id, row.id] })
}
}
console.log(`is selected: ${isSelected}, ${rowStr}`);
}
解决方案
您必须使用地图功能(https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/map):
onSelectAll(isSelected, rows) {
console.log(`is select all: ${isSelected}`);
if (isSelected) {
console.log('Current display and selected data: ');
this.setState({ id: [...this.state.id, ...rows.map(x=>x.id)] })
} else {
console.log('unselect rows: ');
const ids = this.state.id.reduce((acc,id)=>{
return rows.find(x=>x.id === id) ? acc : [...acc,id]
},[])
this.setState({ id: [...ids] })
}
}
推荐阅读
- mysql - 整数列上的聚集索引出奇地慢
- api - 线机器人;如何获取用户LINE ID?
- php - 如何使用php将消息发送到电子邮件
- c - 弯曲过早的EOF
- python - python list_objects() 只接受关键字参数
- sql-server - 将存储在 SQL Server 数据库中的文档导出到 AWS S3 存储桶
- swift - 带有网站静止图像的 iOS 小部件
- lua - 将 LuaSQL 错误捕获到 xpcall 错误处理函数
- sharepoint - PowerApps 附件
- snowflake-cloud-data-platform - 雪花 - 无法使用 snowsql 配置文件设置仓库名称