【问题标题】:How do I maintain the new order of my items after I use drag and drop and refresh the page?使用拖放和刷新页面后,如何保持项目的新顺序?
【发布时间】:2021-01-22 22:03:11
【问题描述】:

我正在使用这个拖放库来重新排序我页面上的文章列表: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, 0, reorderedItem);

    this.setState(items)
  } 

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

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

【问题讨论】:

    标签: reactjs google-cloud-firestore drag-and-drop react-beautiful-dnd


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-23
    • 2019-05-19
    • 2022-01-02
    • 2019-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多