javascript - 在 Firebase 中通过 id 获取特定对象/项目

标签 javascript reactjs firebase firebase-realtime-database

我目前正在使用 Firebase 和 React 构建一个小型网络应用程序,但我无法从 React 客户端获取 Firebase 中的特定项目。

话虽这么说,我已经习惯了 javascript,其中一个简单的提取可能看起来像这样:

const url = 'www.example.com/api/'
const id = '123'
fetch(url + id) <---specific
  .then(res => res.json())
  .then(result => this.setState({results: result})
  .catch(err => console.log(err))

但是,我找不到任何与 firebase 相似的文档。

下面是一个更具体的问题:

class StoryItem extends Component {
   constructor(props) {
   super(props);
    this.state = {
      story: this.props.location.myCustomProps
    };
   }
 componentDidMount() {
   //this should do a fetch request based on the 
  //params id to get the specific item in the firebase
  //right now it is being passed as prop which is unreliable because when page refresh state is reset

  //user should be able to access content 
  //without having to go to previous page
console.log(this.state.story)
}

我尝试从 firebase 获取特定对象的一种方法是:

 componentDidMount(props) {
   const ref = firebase.database().ref("items");
   ref.on("value", snapshot => {
    let storiesObj = snapshot.val();
     storiesObj
      .child(this.props.match.params.id)
      .then(() => ref.once("value"))
      .then(snapshot => snapshot.val())
      .catch(error => ({
         errorCode: error.code,
         errorMessage: error.message
       }));

     });
   }

在这种情况下,错误是 enter image description here

任何帮助将不胜感激,如果有人知道关于 firebase 的任何好的文档,请随时向我发送链接。

谢谢

最佳答案

诀窍是,您不必像以前那样首先获取所有项目的值。 您应该找到 items ref,然后查找您想要的子项并使用 .on.once 获取该子项的值。

类似的东西,基于您的示例代码:

componentDidMount() {
   firebase.database().ref("items");
      .child(this.props.match.params.id)
      .once("value")
      .then(snapshot => snapshot.val())
      .catch(error => ({
         errorCode: error.code,
         errorMessage: error.message
       }));
   }

为了更好地理解,让我们看一下原始代码并尝试找出它出错的原因:

componentDidMount(props) {
   // ⬇️ this ref points to ALL items
   const ref = firebase.database().ref("items");

   // ⬇️ here we're asking for the value stored under the above ref
   ref.on("value", snapshot => {
    let storiesObj = snapshot.val();
     /* so firebase gives us what we ask for, storiesObj
      * is probably a huge js object with all the items inside.
      * And since it's just a regular js object, 
      * it does not have a `child` method on it, thus calling .child errors out.
      */
     storiesObj
      .child(this.props.match.params.id)
      .then(() => ref.once("value"))
      .then(snapshot => snapshot.val())
      .catch(error => ({
         errorCode: error.code,
         errorMessage: error.message
       }));

     });
   }

关于javascript - 在 Firebase 中通过 id 获取特定对象/项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52435658/

相关文章:

javascript - history.pushState 不更新移动 Chrome 上 "share ..."按钮的 url

javascript - 与常规可观察对象相比,Angular HTTP 可观察对象的行为有所不同?

reactjs - 如何在 React Navigation v3 中创建动态选项卡

javascript - 在 Formik 中添加 react-bootstrap 警报以处理提交

javascript - Firebase (Google) 云函数 - 去抖动/节流 database.onWrite() #AskFirebase

firebase - 声明更改会触发 onIdTokenChanged

javascript - 有没有办法通过用户输入连续移动 P5 中的对象?

javascript - Javascript对象在构造过程中可以调用自己的方法吗?

javascript - 禁用 Reactjs 中的依赖下拉选项

dart - 工厂等待 Future 来构造对象