使用拖放和刷新页面后,如何保持项目的新顺序?

问题描述

我正在使用这个拖放库来重新排列我页面上的文章列表https://github.com/atlassian/react-beautiful-dnd

然而,即使我可以上下拖动它们并重新排序,但当我刷新页面时,它们会回到初始状态。

文章来自 Cloud Firestore。

我怎样才能让他们每次搬东西时保持新秩序?

class Articles extends Component {
  constructor(props) {
    super(props);
    this.ref = firebase.firestore().collection("articles");
    this.unsubscribe = null;
    this.onDragEnd = this.onDragEnd.bind(this);
    this.state = {
      articles: [],};
  }

  onCollectionUpdate = (querySnapshot) => {
    const articles = [];
    querySnapshot.forEach((doc) => {
      const { title } = doc.data();
      articles.push({
        key: doc.id,title,});
    });
    this.setState({
      articles,});
    this.onDragEnd = this.onDragEnd.bind(this);
  };

  componentDidMount() {
    this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
  };

  onDragEnd(result) {
    if (!result.destination) return;
        
    const items = this.state.articles;
    const [reorderedItem] = items.splice(result.source.index,1);
    items.splice(result.destination.index,reorderedItem);

    this.setState(items)
  } 

然后在我的 return() 中,我有类似的东西:

<DragDropContext onDragEnd={this.onDragEnd}> ... />

解决方法

您正在从远程来源获取数据。所以你需要在重新排序后更新那个远程源。您必须在 onDragEnd 函数中执行此操作。当前,您仅使用 this.setState(items) 更新本地状态。这就是您在页面刷新时丢失重新排序的原因。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...