【问题标题】:Error reading firebase object converted from firebase array, into React using findIndex()使用 findIndex() 读取从 firebase 数组转换为 React 的 firebase 对象时出错
【发布时间】:2017-02-10 12:24:07
【问题描述】:

我已经从一个数组修改了一个 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);

我该怎么做?

【问题讨论】:

    标签: reactjs firebase firebase-realtime-database


    【解决方案1】:

    没有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"
            }
        }
    }
    

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

    【讨论】:

    • 非常感谢@Frank。您的建议已被记录并采纳
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2021-12-03
    • 2019-05-16
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多