reactjs - 如何在Firebase实时数据库中生成子节点反应原生
问题描述
我在 react native firebase 数据库中上传了一些数据。我必须在其中添加一个带有单独节点的数据数组。我不明白如何执行它。这是我的代码...
firebase.database().ref('Shops/' + firebase.auth().currentUser.uid).push({
UserName: this.state.Uname,
name:this.state.Name,
tagline:this.state.TagLine,
description:this.state.Description,
number:this.state.number,
image_url_logo:this.state.base64_datalogo,
image_url_banner:this.state.base64_data,
})
我想在其中生成另一个名称为products
. 它是一个数组。只想知道如何在此结构中生成带有子节点的数组,请指导。
这是我真正想要的。
解决方案
对于这个用例,它就像在推送到服务器的数据下嵌套数组一样简单。
firebase.database().ref('Shops/' + firebase.auth().currentUser.uid).push({
UserName: this.state.Uname,
name:this.state.Name,
tagline:this.state.TagLine,
description:this.state.Description,
number:this.state.number,
image_url_logo:this.state.base64_datalogo,
image_url_banner:this.state.base64_data,
products: [
{
name: 'rubber duck',
price: '5',
...
},
{
name: 'kitchen sink',
price: '200',
...
}
]
})
但是,当您希望在页面上列出所有商店时,就会出现问题。如果您想获取每家商店的名称、标语、描述、联系电话和图片,即使您不使用商店销售的每件商品,您也必须下载该数据。
而是考虑将商店的产品拆分到单独的数据库位置。
let shopRef = firebase.database().ref('Shops/' + firebase.auth().currentUser.uid).push();
let shopId = shopRef.key; // unique shop ID
let setShopDataPromise = shopRef.set({
UserName: this.state.Uname,
name:this.state.Name,
tagline:this.state.TagLine,
description:this.state.Description,
number:this.state.number,
image_url_logo:this.state.base64_datalogo,
image_url_banner:this.state.base64_data,
});
let setShopItemsPromise = firebase.database().ref('ShopItems/' + firebase.auth().currentUser.uid + '/' + shopId).set([
{
name: 'rubber duck',
price: '5',
...
},
{
name: 'kitchen sink',
price: '200',
...
}
]);
Promise.all([setShopDataPromise, setShopItemsPromise])
.then(() => {
console.log('Shop uploaded successfully');
})
.catch((err) => {
// something went wrong
console.error(err);
});
现在,由于最好在实时数据库中避免使用数组,我将products
通过以下函数运行您的数组,然后将它们传递给 set 以赋予每个项目它自己的唯一产品 ID。产品仍将按相同顺序上传,但会使管理更容易。
function arrayToKeyPairs(arr) {
let rootRef = firebase.database().ref();
let newKey = () => rootRef.push().key;
return arr.reduce((acc, v) => {
acc[newKey()] = v
return acc;
}, {});
}
推荐阅读
- json - 从 JSON 执行 Groovy 脚本
- c# - 如何在两个不相邻的区域上画一个字符串
- node.js - Web 驱动程序 - 如何覆盖 Microsoft Edge 的用户代理
- php - Laravel 数据库迁移用户可能来自其他类型
- java - 如何将带有参数的https post请求发送到api
- android - 如何使用 contentObserver 和 contentResolver 从 Messages 中读取已发送短信的内容?
- javascript - 在不使用 GTM dataLayer 的情况下触发自定义事件以激活 Google Optimize
- android - 如何保存照片?
- swagger - 如何在“../v2/api-docs”json 生成文件中启用 SecurityDefinitions
- datetime - 数据表中日期时间列的 order by 问题