我目前正在構建一個接口來構建問卷。問卷中的每個問題是存儲在火力地堡結構如下:重新排序存儲在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),您可能需要進行某種「重置」操作,以重新排序它們。 –