從數組中刪除指定對象元素,應用場景:刪除前端增行沒有保存導數據庫的表格數據

addRows() {
        const length = this.props.store.newDetailList.length;
        let obj = {
            'ids': length,
               ... //其他鍵值對
        };
        this.props.store.docDetailList.unshift(obj);
    };

首先新增一條數據,如上;

 

表格中的多選框,在state 中設被選中的多選框,刪除時及時重置爲空數組

const {selectedRowKeys} = this.state;
const rowSelection = {
      selectedRowKeys,
          onChange: (selectedRowKeys, selectedRows) => {
                let selectedRowsIds = [];
                this.setState({selectedRowKeys:selectedRowKeys})
                for (let i = 0; i < selectedRows.length; i++) {
                    selectedRowsIds.push(selectedRows[i].id||selectedRows[i].ids)
                }
                this.props.store.detailSelectedRowsId = selectedRowsIds;
            },
            getCheckboxProps: record => ({
                disabled: record.name === 'Disabled User',
                name: record.name,
            }),
};

//從數組中刪除指定鍵值的對象   

removeObjFromArrayByKeyValue(arr, attr, value) {  //數組,屬性(根據哪個key值刪的),屬性值(key 對應的value 是多少)

     var index = 0;

    for (let i = arr.length - 1; i > -1; i--) {

        if (arr[i][attr] == value) {

           index = i;

           break;

        }

    }

    arr.splice(index, 1);

    };


現在需要根據已經傳入數據庫的值id和沒有傳入的ids兩個key 值來操作數組

removeObjFromArrayByKeyValue(arr,value) {  //數組,屬性,屬性值
        var index = 0;
        for (let i = arr.length - 1; i > -1; i--) {
//我改成了ids id,當數組中是ids的時候,按ids來刪,id同理
            if (arr[i].id == value||arr[i].ids == value) {
                index = i;
                break;
            }
        }
    arr.splice(index, 1);
};


    delRows() {
        const { detailSelectedRowsId } = this.props.store;
        if (detailSelectedRowsId.length == 0) {
            GlobalStore.showError(intl.get('SELECT_ONE_TO_DEL'))
        } else {
            this.setState({selectedRowKeys:[]})
            for (let i = 0; i < detailSelectedRowsId.length; i++) {
  //調用函數
this.removeObjFromArrayByKeyValue(this.props.store.docDetailList,detailSelectedRowsId[i])//刪除選中的數據
            }
            this.setState({
                flag: !this.state.flag
            })
            let delflag=true;//這是從來判斷有空數據不能保存的
            for(let i=0;i<this.props.store.detailSelectedRowsId.length;i++){ 
                if(!this.props.store.detailSelectedRowsId[i]){
                    delflag=false;
                    break;
                }
            } 
            if(delflag){
                //沒有空數據的時候就調用後端接口
                this.props.store.deleteDetails(this.props.store.detailSelectedRowsId)
            }else{
                return 
            }
        }
    };

 

發佈了37 篇原創文章 · 獲贊 11 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章