首页 > 解决方案 > 如何在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. 它是一个数组。只想知道如何在此结构中生成带有子节点的数组,请指导。

在此处输入图像描述

这是我真正想要的。

标签: reactjsfirebasereact-nativefirebase-realtime-database

解决方案


对于这个用例,它就像在推送到服务器的数据下嵌套数组一样简单。

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

推荐阅读