选择时删除数组中的ID-取消选择

时间:2019-04-12 13:04:16

标签: reactjs redux react-redux

我正在寻找一种方法,当取消选择一行时,用于删除数组中的数字。

  

选择时> 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}`);
}

3 个答案:

答案 0 :(得分:1)

如果isSelect为false,则必须在状态下将数组设置为不包含选定的行ID。过滤功能帮您完成。

    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] })
        }else{
          this.setState({ id: [...this.state.id.filter(x=>x!==row.id)] })
        }
      }
      console.log(`is selected: ${isSelected}, ${rowStr}`);
    }

答案 1 :(得分:1)

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

答案 2 :(得分:0)

当我使用

  

this.setState({id:[... this.state.id,rows [i] .id]})

他只检索该部分的最后一个ID

onSelectAll(isSelected, rows) {
        console.log(`is select all: ${isSelected}`);
        if (isSelected) {
            console.log('Current display and selected data: ');
        } else {
            console.log('unselect rows: ');
        }
        for (let i = 0; i < rows.length; i++) {
            console.log(rows[i].id);
            this.setState({ id: [...this.state.id, rows[i].id] })
        }
    }