谁能建议将 React Drag/Drop 列表与 Redux 的动态值集成的最佳方法?

Can anyone advise on the best way to integrate React Drag/Drop Lists with dynamic values from Redux?

我需要可排序 drag/drop 组件能够在用户从另一个容器单击按钮时使用新值重新呈现,并且仍然保留 drag/drop 功能。例如,如果列表最初包含 [a, b, c],我需要它在用户单击将重新呈现列表为 [d, e, f, g] 的按钮时仍然有效。

我 运行 遇到了与 react-sortable-hocreact-beautiful-dnd 和其他一些人相同的问题。所有这些库都使用一个数组来填充它们的拖放列表组件,在基本示例中通常命名为 this.state.items。他们使用一个名为 onSortEnd 的函数来处理项目的重新排列。下面是 react-sortable-hoc 的基本代码示例,其中包括我在 render() 中的更新 this.state.items:

import React, {Component} from 'react';
import {render} from 'react-dom';
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 SelectedItem extends Component {
  state = {
    items: ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6'],
  };
  onSortEnd = ({oldIndex, newIndex}) => {
    this.setState({
      items: arrayMove(this.state.items, oldIndex, newIndex),
    });
  };
  render() {

// MY CODE ADDITIONS!! THIS IS WHERE THE LIST ITEM GETS UPDATED.

    this.state.items = [this.props.selectedItem.node.title,
                this.props.selectedItem.node.subtitle,
                this.props.selectedItem.treeIndex]; 

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

function mapStateToProps(state)
{
    return {
        selectedItem: state.activeItem
    };
}

export default connect(mapStateToProps)(SelectedItem);

一开始 drag/drop 一切正常。但是,如果我在 render() 中更改 items[] 的值,则新列表会正确呈现。但是 drag/drop 失败了。看起来拖动时会起作用;所选元素移动并且目标位置看起来会接受它但是 onMouseRelease 一切都会恢复到原来的状态。

我在数组移动后放置了 console.log 命令,以确认 items 中的列表已按需要重新排序。它只是在视觉上不会发生。 dragging/dropping.

时没有控制台错误

如有任何帮助,我们将不胜感激。

我通过利用 getDerivedStateFromProps 生命周期方法更新项目状态解决了这个问题。

我只是通过将 Draggable key 属性从这种格式 dragItem-${index} 更改为这种格式来解决这个问题:dragItem-${item.id}。每个项目的 id 都是唯一的,因此这似乎可以使事物更新和正确呈现。来自 React 文档 (https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html):

When a key changes, React will create a new component instance rather than update the current one.

我可以看到我的状态正在正确更新,但是带有 react+beautiful-dnd 的东西没有正确重新渲染(除非你刷新),这是罪魁祸首。