Firebase的React同步问题



import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import {Card, CardContent, CardActions, Typography, IconButton} from '@material-ui/core';
import firebase from './firebase';
class LikeMusicList extends React.Component{

render () {
let db = firebase.firestore();
let snapshot = db.collection("likes");
let list = []
snapshot.get().then(function(querySnapshot) {
if (querySnapshot) {
querySnapshot.forEach(function(item){
fetch(`https://itunes.apple.com/lookup?id=${item.id}&entity=album`).then(r => r.json()).then(r => {
list.push(r.results[0]);
console.log(list);
}).catch(e => console.log(e));
})
}
else {
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
//console.log(list);
return (
<div>
{console.log(list)}
{list.map(item => {
<Card key={item.collectionId} className={classes.card}>
<CardContent>
<Typography variant="subtitle1"> {item.artistName}</Typography>
<Typography variant="subtitle2"> {item.collectionCensoredName}</Typography>
</CardContent>
<img src = {item.collectionViewUrl} alt = {item.collectionName}></img>
</Card>
})}
</div>
);
};
}
export default LikeMusicList

我想通过在Itunes中获取专辑来渲染这些数据。但是由于同步问题,返回变量'list'是空的。我认为代码'snapshot.get()。~'在return之前执行,但结果与此相反。如何解决这个问题?

您可以通过使用state并将firestore函数移动到名为componentDidMount的react生命周期函数来解决这个问题:

import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import {Card, CardContent, CardActions, Typography, IconButton} from '@material-ui/core';
import firebase from './firebase';
class LikeMusicList extends React.Component{

state = {
list: []
}

componentDidMount() {
let db = firebase.firestore();
let snapshot = db.collection("likes");
snapshot.get().then(function(querySnapshot) {
if (querySnapshot) {
querySnapshot.forEach(function(item){
fetch(`https://itunes.apple.com/lookup?id=${item.id}&entity=album`).then(r => r.json()).then(r => {
this.setState({
list: r.results[0]
})
console.log(r.results[0]);
}).catch(e => console.log(e));
})
}
else {
console.log("No such document!");
}
}).catch(function(error) {
console.log("Error getting document:", error);
});
}

render () {
return (
<div>
{this.state.list.map(item => {
<Card key={item.collectionId} className={classes.card}>
<CardContent>
<Typography variant="subtitle1"> {item.artistName}</Typography>
<Typography variant="subtitle2"> {item.collectionCensoredName}</Typography>
</CardContent>
<img src = {item.collectionViewUrl} alt = {item.collectionName}></img>
</Card>
})}
</div>
);
};
}
export default LikeMusicList

最新更新