1

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

app.js 构造函数

将状态传递给监视列表组件

继承人的代码:

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>
    )
  }
}
4

1 回答 1

1

render() {...}不是获取数据的地方。将其移至componentDidMount如下:


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

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

    movieRef.on("value", snapshot => {

      // I keep your logic here
      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
      });



    });
  }

  render() {

    const { movies } = this.state;


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

于 2019-03-13T05:08:32.513 回答