【问题标题】:React fetch Firebase get unique key valueReact fetch Firebase 获取唯一键值
【发布时间】:2020-05-17 17:08:59
【问题描述】:

有谁知道如何从 firebase 数据库中获取唯一键值?我想将其存储在 state 中并将其打印到 console.log 中。

这是唯一键的示例

这是代码,我只是想在控制台中显示它

import React, { Component } from "react";

export class Test extends Component {
  constructor(props) {
    super(props);

    this.state = {
      newId: ""
    };
  }

  componentDidMount() {
    fetch("https://redditclone-project.firebaseio.com/data.json", {
      method: "get",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json"
      }
    })
      .then(res => res.json())
      .then(res => {
        console.log(res);
      });
    console.log('value key, ex:-LzpvyLJnKgDllnTE-eW');
  }
  render() {
    return <div></div>;
  }
}

export default Test;

谢谢

编辑:内部资源 并添加了我的 firebase 链接

【问题讨论】:

  • 你从console.log(res);得到什么输出?
  • 我还注意到您分享的 JSON 屏幕截图中没有 linkfirebase.json
  • 已编辑,还加上 console.log(res)

标签: javascript reactjs firebase firebase-realtime-database fetch


【解决方案1】:

如果您只想从 JSON 中打印密钥,可以使用 Object.keys():

.then(res => res.json())
.then(res => {
  console.log(Object.keys(res));
});

由于Object.keys() 返回一个数组,因此您还可以使用例如Array.forEach() 来循环这些键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2022-12-02
    • 2020-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多