如何在 React Native 中设置 firebase 实时数据库 eventListener

how to set up firebase realtime database eventListener in react native

我正在尝试向我的 React 本机应用程序添加一个事件侦听器,它会在更改时触发,但在我刷新应用程序之前不会触发。我想我没有正确设置事件侦听器,但我不知道该怎么做。

这是我的代码:

render(){

    Firebase.database()
    .ref('/UserToQuestion/' + Firebase.auth().currentUser.uid)
    .orderByChild("Question")
    .on('value', snapshot => {

         console.log('-----------');



        var i = 0
        snapshot.forEach(function(childSnapshot) {



            var childData = childSnapshot.val();



            titlesArray.push(childData.Title)
            contentArray.push(childData.Question)
            dataArray.push({title:titlesArray[i],content:contentArray[i]})
            i++
            console.log( titlesArray);



   });

 })

将它放在 render 方法之外会导致 currentUser.uid 未定义的错误,但我认为仅在 render 上触发的侦听器才是问题所在,那么我如何让它始终被触发?

谢谢

您需要对其进行设置,以便在构建组件时创建 firebase 引用。我认为这样的事情应该有效。我添加了评论来解释我所做的事情:

class MySuperAwesomeClass extends React.Component {
  // this will be a fixed reference you can use to attach/detach the listener
  firebaseRef;

  constructor(props) {
    super(props);

    // assign a reference to this component's firebaseRef member
    this.firebaseRef = Firebase.database().ref(
      `/UserToQuestion/${Firebase.auth().currentUser.uid}`
    );

    // grab the data from the server and call this.onFirebaseValueChanged every time it changes
    this.firebaseRef.orderByChild("Question").on("value", this.onFirebaseValueChanged);
  }

  componentWillUnmount() {
    // detach all listeners to this reference when component unmounts (very important!)
    this.firebaseRef.off();
  }

  onFirebaseValueChanged = snapshot => {
    console.log("-----------");
    // I created these arrays because they didn't seem to exist
    const titlesArray = [];
    const contentArray = [];
    const dataArray = [];

    // use let instead of var because it's changing
    let i = 0;
    snapshot.forEach(childSnapshot => {
      // use const instead of var
      const childData = childSnapshot.val();

      titlesArray.push(childData.Title);
      contentArray.push(childData.Question);
      dataArray.push({title: titlesArray[i], content: contentArray[i]});
      i++;
      console.log(titlesArray);
    });
  };

  render() {
    return <Text>Render method shouldn't be talking to the server!</Text>;
  }
}