Как настроить базу данных событий в реальном времени в Firebase - PullRequest
0 голосов
/ 16 апреля 2020

Я пытаюсь добавить прослушиватель событий в свое собственное приложение реагирования, которое срабатывает при изменении, но не запускается, пока я не обновлю sh приложение. Я думаю, что неправильно настраиваю прослушиватель событий, но я не знаю, как еще это сделать.

Вот мой код:

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 не определен, но я думаю, что проблема в том, что слушатель запускается только при рендеринге, это проблема, так как бы я всегда включал его?

Спасибо

1 Ответ

0 голосов
/ 16 апреля 2020

Вам нужно настроить его, чтобы вы создавали ссылку на 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>;
  }
}
...