【问题标题】:How to move a javascript a whole object in an array when using the splice function? (React.js)使用 splice 函数时如何将 javascript 移动到数组中的整个对象? (反应.js)
【发布时间】:2020-08-23 02:24:42
【问题描述】:

我正在使用 React.js 中的拖放交互。我正在使用下面的 onDragEnd 函数完成拖动时调用的 splice 函数对“行”数组进行重新排序:

onDragEnd = (result) => {
    const { destination, source, draggableId, type } = result;
    if (!destination) {
        return;
    }
    if (
        destination.draggableId === source.droppableId &&
        destination.index === source.index
    ) {
        return;
    }

    if (type === "row") {
        const newRowOrder = Array.from(**this.state.currentRows**);
        newRowOrder.splice(source.index, 1);
        newRowOrder.splice(destination.index, 0, **draggableId**);

        const newState = {
            ...this.state,
            currentRows: newRowOrder,
        };

        this.setState(newState);
    }
};

在调用 onDragEnd 函数之前,currentRow 状态如下所示: currentRow state before onDragEnd

调用该函数时,拼接函数起作用(我认为),但它不会移动数组中的整个对象,只是移动 ID。拼接函数中使用的draggableId是需要移动的对象的ID。

调用 onDragEnd 函数后,currentRow 状态如下所示: currentRow state after onDragEnd

可以将整个对象移动到新索引吗?

【问题讨论】:

    标签: javascript arrays reactjs splice


    【解决方案1】:

    我认为您只是插入了 draggableId newRowOrder.splice(destination.index, 0, **draggableId**); 您可以使用 Array.find 函数找到整个对象并插入整个对象

    onDragEnd = (result) => {
        const { destination, source, draggableId, type } = result;
        if (!destination) {
            return;
        }
        if (
            destination.draggableId === source.droppableId &&
            destination.index === source.index
        ) {
            return;
        }
    
        if (type === "row") {
            const draggableRow = this.state.currentRows.find(row => row.id === draggableId);
            const newRowOrder = Array.from(this.state.currentRows);
            newRowOrder.splice(source.index, 1);
            newRowOrder.splice(destination.index, 0, draggableRow);
    
            const newState = {
                ...this.state,
                currentRows: newRowOrder,
            };
    
            this.setState(newState);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2014-02-23
      • 2017-06-05
      • 2022-01-26
      • 2019-06-16
      • 1970-01-01
      相关资源
      最近更新 更多