在React JS中从Firebase数据库信息设置状态

时间:2019-03-13 04:00:55

标签: javascript reactjs firebase themoviedb-api

我正在尝试学习反应,并且正在使用firebase数据库和auth以及movie db API创建一个Web应用程序。我可以让用户单击电影并将该电影添加到他们的监视列表中,以“将该电影的信息发送到firebase”。现在,我正在尝试检索该信息,并且我这样做很成功,但是我的代码当前导致浏览器锁定并崩溃,并不断记录日志,因此我需要强制退出。我不确定我要去哪里错了?当我将呈现器中的代码放入构造函数或componentDidMount中时,this.props.user返回null。我很困惑:(

app.js constructor

passing state to watchlist component

此处是代码:

import React, { Component } from 'react'
import firebase from '../config/Firebase';

import { Container } from 'react-bootstrap';

import WatchlistMovie from './WatchlistMovie';

export default class Watchlist extends Component {
  constructor(props){
    super(props);
    this.state = {
      movies: [],
    }
  }

  render() {

    const movieRef = firebase.database().ref(`watchlist/${this.props.user}`);

    movieRef.on("value", snapshot => {
      let movies = snapshot.val();

      console.log(movies);

      let newState = [];

      for(let movie in movies){
        newState.push({
          id: movies[movie].id,
          title: movies[movie].title,
          rating: movies[movie].rating,
          poster: movies[movie].poster
        });
      }

      this.setState({
        movies: newState
      });

      console.log(this.state.movies);

    });


    return (
      <div>
        <Container>
            <WatchlistMovie
              ... send data from firebase to this individual movie component
            />
        </Container>
      </div>
    )
  }
}

0 个答案:

没有答案