使用 findIndex() 读取从 firebase 数组转换为 React 的 Firebase 对象时出错



我已经从数组中修改了一个火碱结构

{
   "posts" : [
   {
      "code" : "BAcyDyQwcXX",
      "caption" : "Lunch #hamont",
      "likes" : 56,
      "id" : "1161022966406956503",
      "display_src" : "https://test1.jpg"
   },
   {
      "code" : "BAcJeJrQca9",
      "caption" : "Snow! ⛄️🌨❄️ #lifewithsnickers",
      "likes" : 59,
      "id" : "1160844458347054781",
      "display_src" : "https://test2.jpg"
   },
   ]
}

到"展平"对象

{
    "posts" : {
        "1161022966406956503" : {
            "code" : "BAcyDyQwcXX",
            "caption" : "Lunch #hamont",
            "likes" : 56,
            "display_src" : "https://test1.jpg"
        },
        "1160844458347054781" : {
            "code" : "BAcJeJrQca9",
            "caption" : "Snow! ⛄️🌨❄️ #lifewithsnickers",
            "likes" : 59,
            "display_src" : "https://test2.jpg"
        }
    }
}

现在希望重构以下代码,以适应对 Firebase 对象而不是数组的处理:

 const { postId }  = this.props.params;
 const i = this.props.posts.findIndex((post) => post.code === postId);

我该怎么做?

没有findIndex方法,因为你不再有数组了。

要查找值的,请使用:

const posts = this.props.posts;
const key = Object.keys(posts).find((prop) => posts[prop].code === postId);

但是,当帖子已经具有有效密钥时,为什么要将帖子存储在时间戳下?我建议将每个帖子存储在该键下:

{
    "posts" : {
        "BAcyDyQwcXX" : {
            "caption" : "Lunch #hamont",
            "likes" : 56,
            "display_src" : "https://test1.jpg"
        },
        "BAcJeJrQca9" : {
            "caption" : "Snow! ⛄️🌨❄️ #lifewithsnickers",
            "likes" : 59,
            "display_src" : "https://test2.jpg"
        }
    }
}
然后,您

不再需要查找帖子的索引/键,因为您已经拥有存储它的键。

最新更新