我目前正在构建一个接口来构建问卷。问卷中的每个问题是存储在火力地堡结构如下:重新排序存储在Firebase中的动态集合/列表中的项目
questions
| - {key}
| - lastModified // <-- When the question was created, last updated
| - position // <-- The position in which the question appears on frontend
| - question // <-- Question text content
| - uid // <-- The unique key with which it is saved to firebase
/* ... */
/* Repeat for n questions! */
/* ... */
管理员可以添加,删除,更新和重新排序的问题。
当管理员删除的问题时,我必须增加所删除问题下所有问题的位置值。
我接近这个的方法是修改我本地存储的列表副本(在我的情况下,克隆存储在Redux状态中的数组),执行必要的调整,然后将其推送到Firebase,覆盖现有的“问题”数据组。
这里是我的代码:
// Remove question action creator
export function removeQuestion(key, questions) {
return (dispatch) => {
dispatch({type: REMOVE_QUESTION});
const updatedQuestions = questions.filter((question) => {
return !(question.uid === key); // I remove the target item here.
}).map((question, index) => {
return {
lastModified: question.lastModified,
position: index, // I update the position of all other items here.
question: question.question,
stageId: question.stageId,
uid: question.uid
};
});
questionsRef.set(updatedQuestions) // And then I save the entire updated dataset here.
.then(() => dispatch(removeQuestionSuccess(key)))
.catch(error => dispatch(removeQuestionError(key, error)));
};
}
但是,有没有这样做的更好的办法?
这肯定会使保持位置更简单,以下项目重新定位或删除。感谢您的建议。 我以前见过这个,虽然不是使用浮点数,而是使用一个序数,而是使用100或10的数值(例如A:10,B:20,C:30)。 我现在看到浮点的优点是总是可以计算中点,相邻定位项之间的差异可以变得越来越小。但它有没有突破?我想这取决于你如何处理你的浮点精度? –
这里有一些理论上的限制/重新排序的次数,它会中断,但它需要大量的最坏情况下的重排序(我认为)。如果达到某个阈值(例如,如果兄弟姐妹之间的距离小于等于0.00001),您可能需要进行某种“重置”操作,以重新排序它们。 –