可反应可分配的 - 保持新排序秩序,而无需实验类属性



以下配置没有抛出任何错误,但新排序顺序却没有维护。拖动和相关的动画运行良好,但是排序顺序本身永远不会永久变化。

我已经从https://www.npmjs.com/package/reeact-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} />;
    }
}

问题在OnSortend回调中:

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

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

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

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