首页 > 解决方案 > react-sortable-hoc -- 在没有实验类属性的情况下保持新的排序顺序

问题描述

以下配置未引发任何错误,但未维护新的排序顺序。拖动和关联的动画效果很好,但排序顺序本身永远不会改变。

我已经从https://www.npmjs.com/package/react-sortable-hoc的示例稍微修改了我的代码。(我将一些代码移到构造函数中,以解决与实验类属性相关的错误。)

有任何想法吗?

import {
    SortableContainer,
    SortableElement,
    arrayMove,
} from 'react-sortable-hoc';

const SortableItem = SortableElement(({value}) => <li>{value}</li>);

const SortableList = SortableContainer(({items}) => {
    return (
        <ul>
            {items.map((value, index) => (
                <SortableItem key={`item-${index}`} index={index} value={value} />
            ))}
        </ul>
    );
});

class SortableComponent extends Component {

    constructor(props) {
        super(props);
        this.state = {};
        this.state.items = [
            "Gold",
            "Crimson",
            "Hotpink",
            "Blueviolet",
            "Cornflowerblue",
            "Skyblue",
            "Lightblue",
            "Aquamarine",
            "Burlywood"
        ];
        this.onSortEnd = this.onSortEnd.bind(this);
    }

    onSortEnd(oldIndex, newIndex) {
        this.setState(({items}) => ({
            items: arrayMove(items, oldIndex, newIndex),
        }));
    }

    render() {
      return <SortableList items={this.state.items} onSortEnd={this.onSortEnd} />;
    }
}

标签: reactjsreact-sortable-hoc

解决方案


问题出在 onSortEnd 回调中:

onSortEnd(oldIndex, newIndex) {
  this.setState(({items}) => ({
    items: arrayMove(items, oldIndex, newIndex),
  }));
}

您需要将函数的参数更改(oldIndex, newIndex)({ oldIndex, newIndex })

来自 github 文档 ( https://github.com/clauderic/react-sortable-hoc ): onSortEnd - 排序结束时调用的回调。function({oldIndex, newIndex, collection}, e)

请注意函数签名和您的实现的差异,oldIndex并且newIndex是通过在第一个参数上使用对象解构来分配的。通过使用函数的第二个参数,因为oldIndex它实际上将e作为值,在更新数组的顺序时显然不能用作索引!


推荐阅读