React JS 上的 Firebase Firestore 双循环数据
2020-04-18
196
我有这样的代码 Model.js
import firebase from '../config/Firebase'
class Dashboard {
GetAllBlog() {
return firebase.collection('blogs').get()
}
}
export default new Dashboard()
然后,我将模型返回到 home.js
import React from 'react';
import Index from './components/index'
import CardOverview from './components/CardOverview'
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container'
import Paper from '@material-ui/core/Paper'
import Grid from '@material-ui/core/Grid'
import Typography from '@material-ui/core/Typography';
import DashboardService from '../services/dashboard'
const styles = theme => ({
root: {
padding: theme.spacing(3, 2),
},
row: {
padding: theme.spacing(3, 2),
}
});
class Home extends React.Component {
state = {
blogs: []
}
componentDidMount() {
DashboardService.GetAllBlog()
.then(snapshot => {
this.setState({
blogs: snapshot
})
})
.catch(err => {
console.log('Error getting documents', err);
});
}
render() {
const { classes } = this.props
const {
blogs
} = this.state
blogs.forEach(element => {
console.log("blogs", element.data().title)
});
return (
.......
但是当我像这样使用 foreach 时,我得到了 Double
实际上,我有这样的数据(两个数据)
我看看如何为了简化将所有快照转换为数组的过程(我可以从 firebase 创建连接数组),但我很困惑,为什么会出现这种双循环,但它循环 2 次,但有一次,它的循环基于长度
1个回答
这是因为状态被改变了 2 次,所以每次改变状态时都会执行渲染
Lucas Matos
2020-04-18