gpt4 book ai didi

javascript - 在 React js 中从 firebase 数据库信息设置状态

转载 作者:行者123 更新时间:2023-11-30 19:43:46 24 4
gpt4 key购买 nike

我正在尝试学习 React,我正在使用 firebase 数据库和 auth 以及电影 db api 创建一个网络应用程序。我能够让用户点击一部电影并将该电影添加到他们的监视列表中“将该电影的信息发送到 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>
)
}
}

最佳答案

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

关于javascript - 在 React js 中从 firebase 数据库信息设置状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55134187/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com