我修改了数组中的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);
我该怎么做?
答案 0 :(得分: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"
}
}
}
然后您不再需要查找帖子的索引/键,因为您已经拥有了存储它的密钥。