在使用拖放和刷新页面后,如何维护项目的新顺序?



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

您正在从远程数据源获取数据。所以你需要在重新排序后更新远程源。你必须在onDragEnd函数中做这个。目前,您只使用this.setState(items)更新本地状态。这就是为什么你在页面刷新时失去了重新排序。

最新更新