reactjs - 使用拖放和刷新页面后,如何保持项目的新顺序?
问题描述
我正在使用这个拖放库来重新排序我页面上的文章列表: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)
。这就是您在页面刷新时失去重新排序的原因。
推荐阅读
- api - Google Cloud Platform 合作伙伴互连 API - 只有获得批准的合作伙伴才能创建类型为 PARTNER 的互连
- bash - 将数据从 for 循环传递到 zenity 进度
- javascript - jquery 带走导航栏
- django - 如何在 urls django i18n 中获取所有语言?
- scala - 如何在 scala 中创建 map[String,Class] 并动态创建其对象
- bash - for循环bash脚本并行
- java - 删除并重新创建文件/目录
- python - 使用 flask_dance 进行 OAuth2 的 SSLError
- regex - 需要正则表达式来匹配 Oracle 12cR1 源代码中的确切表名
- android - 在 Genymotion 地图服务中搜索城市目前无法正常工作