【问题标题】:how to set up firebase realtime database eventListener in react native如何在本机反应中设置firebase实时数据库事件监听器
【发布时间】:2020-04-16 09:01:15
【问题描述】:

我正在尝试向我的 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);



   });

 })

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

谢谢

【问题讨论】:

    标签: reactjs firebase react-native firebase-realtime-database event-listener


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-08
      • 2018-11-19
      • 1970-01-01
      • 2016-04-30
      相关资源
      最近更新 更多