在Firebase中按ID获取特定的对象/项目

时间:2018-09-21 02:09:57

标签: javascript reactjs firebase firebase-realtime-database

我目前正在使用Firebase和React构建一个小型Web应用程序,但是我无法从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上的任何文档,任何帮助也将不胜感激,请随时向我发送链接。

谢谢

1 个答案:

答案 0 :(得分:3)

诀窍是,您不必像这样做一样先获取所有项目的价值。 您应该找到items引用,然后查找所需的孩子,并使用.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
       }));

     });
   }