首页 > 解决方案 > 选择时删除数组中的 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}`);
}

标签: reactjsreduxreact-redux

解决方案


您必须使用地图功能(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] })
    }
}

推荐阅读