【问题标题】:Firebase does not save empty arrayFirebase 不保存空数组
【发布时间】:2022-06-11 18:20:09
【问题描述】:

您好,我有一个问题,我正在使用 Firebase 和 React 制作应用程序。问题是我想要评论数组,但是在创建项目时它是空的。我怎样才能解决这个问题并有一个空数组,然后在添加 cmets 后更新这个数组。

代码很多。

 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);
    },

【问题讨论】:

    标签: reactjs typescript firebase


    【解决方案1】:

    为什么不保存一个空数组?


    我没有太多的知识,所以我只是用Java解释它。

    当你像这样创建一个新的空数组时:

    List array = new ArrayList<>();
    

    它的大小是 0。而且,对于空数组,0 可以说是 null。现在,Firebase 会忽略 null 或 0 大小的数组,因为它没有任何内容可显示在控制台中。

    那我该怎么办?


    做到这一点并不难。现在,在你的情况下,因为数据库中没有这样的键,它会给出 null 然后你尝试使用它,你会得到一个异常。这是每个开发人员都想防止的。所以解决方案可以是在数据库中存储一个boolean 和其他键来检查数据是否有数组。刚刚创建帖子时,没有 cmets。您可以将其设置为false。现在,当用户添加评论时,将其设置为 true

    现在在获取 cmets 时,首先检查 boolean 是否为真。如果为真,则获取 cmets。或者直接忽略。

    代码?


    如前所述,我没有太多使用 React.JS,因此无法提供代码。但我希望你能做到,因为你已经自己做了这么多。

    【讨论】:

    • 谢谢 我明白你的意思。我会自己做。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多