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

Lul*_*aby 1 javascript firebase reactjs firebase-realtime-database

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

话虽如此,我已经习惯了 javascript,其中一个简单的 fetch 可能看起来像:

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))
Run Code Online (Sandbox Code Playgroud)

但是,我无法找到有关与 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)
}
Run Code Online (Sandbox Code Playgroud)

我尝试从 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
       }));

     });
   }
Run Code Online (Sandbox Code Playgroud)

在这种情况下,错误是 在此处输入图片说明

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

谢谢

Gle*_*ost 5

诀窍是,您不必像您一样首先获得所有项目的价值。您应该找到itemsref,然后查找您想要的孩子并使用.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
       }));
   }
Run Code Online (Sandbox Code Playgroud)

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

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

     });
   }
Run Code Online (Sandbox Code Playgroud)