【发布时间】:2019-03-13 04:00:54
【问题描述】:
我正在尝试学习 react,我正在创建一个带有 firebase 数据库和身份验证以及电影 db api 的网络应用程序。我可以让用户点击一部电影并将该电影添加到他们的监视列表中“将该电影的信息发送到 Firebase”。现在我正在尝试检索该信息,并且我成功地这样做了,但是我的代码当前导致浏览器锁定并崩溃并不断记录,我需要强制退出。我不确定我哪里出错了?当我将渲染中的代码放入构造函数或 componentDidMount 时,this.props.user 返回 null。我很困惑:(
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>
)
}
}
【问题讨论】:
-
你能发布错误跟踪吗?
-
终端没有错误,控制台只是不断记录(this.state.movies)导致浏览器崩溃
-
嗨,您不能在渲染函数中调用 setState,因为更改状态会重新渲染组件,因此您会得到一个无限循环,您的渲染函数调用 setState 并且由于 setState,您的渲染函数会再次被调用.您需要将此代码放入 componentDidMount 生命周期函数中
-
嘿 Rishabh,当我将它放入 componentDidMount 生命周期时,this.props.user 被接收为 null
-
你能显示道具被传递的地方吗?
标签: javascript reactjs firebase themoviedb-api