您好,我有一個問題,我正在使用 Firebase 和 React 制作應用程式。問題是我想要評論陣列,但是在創建專案時它是空的。我怎樣才能解決這個問題并有一個空陣列,然后在添加評論后更新這個陣列。
有很多代碼。
const onSubmitHandler = (e: React.FormEvent): void => {
e.preventDefault();
if (user?.displayName) {
const recipe: Recipe = {
username: user.displayName,
title: title,
type: type,
description: description,
id: Math.random(),
time: time,
ingredients: ingredients,
stars: Math.floor(Math.random() * 6) 1,
steps: steps,
comments: [],
};
dispatch(recipeAction.addRecipe(recipe));
dispatch(sendData(recipe));
navigate("/");
}
};
Redux action
export const fetchRecipes = () => {
return async (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
dispatch(uiAction.isLoading(true));
const getRecipes = async () => {
const response = await fetch(
*FIREBASE API*
);
const data = response.json();
return data;
};
try {
const data = await getRecipes();
console.log(data);
if (data) {
for (const key of Object.keys(data)) {
dispatch(recipeAction.replaceRecipes(data[key]));
}... other not needed code.
Redux slice
replaceRecipes(state, action: PayloadAction<Recipe>) {
const fetchedRecipe = action.payload;
state.recipes.push(fetchedRecipe);
},
uj5u.com熱心網友回復:
為什么它不保存一個空陣列?
我沒有太多的知識,所以我只是用java解釋它。
現在說到重點。現在,當您像這樣創建一個新的空陣列時:
List array = new ArrayList<>();
它的大小是 0。而且,對于空陣列,0 可以說是 null。現在,firebase 會忽略 null 或 0 大小的陣列,因為它在控制臺中沒有任何內容可顯示。
那我該怎么辦?
做到這一點并不難。現在,在你的情況下,因為資料庫中沒有這樣的鍵,它會給出 null 然后你嘗試使用它,然后是一個例外。這是每個開發人員都想防止的。因此解決方案可以是將 aboolean與其他鍵一起存盤在資料庫中,以檢查資料是否具有陣列。剛創建帖子時,沒有評論。您可以將其設定為false. 現在,當用戶添加評論時,將其設定為true.
現在在獲取評論時,首先檢查是否boolean為真。如果為真,請獲取評論。否則就直接忽略。
代碼?
如前所述,我沒有使用React JS太多所以無法提供代碼。但我希望你能做到,因為你自己已經做了很多。
快樂編碼??
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/454275.html
