我在useEffect中从Firebase获取数据。
在useEffect中,我使用useState以某种状态存储数据(数组)。
我想在我的rfc渲染方法中使用此数据,但首先需要reduce()它。我试图在原始useEffect(在获取数据的位置相同),其他useEffect或什至在我的render方法中减少它。
这些实际上都无法实现。我的累加器参数在我的reduce函数中保持空白。拜托,我真的需要一些帮助。
import React, { useState, useEffect } from 'react'
import { Grid, Paper, Typography, Table, TableBody, TableCell, TableHead, TableRow } from '@material-ui/core'
import firebase from './../firebase'
const db = firebase.firestore()
export default function Scores(props) {
let { match } = props
let [currentEvent, setcurrentEvent] = useState(null)
let [records, setRecords] = useState([])
let [data, setdata] = useState(null)
useEffect(() => {
console.log("effet 1")
db.collection('events').doc(match.params.id)
.onSnapshot(doc => {
setcurrentEvent(currentEvent = { ...doc.data(), uid: doc.id })
setRecords(records = doc.data().records)
})
}, [])
useEffect(() => {
console.log(records)
let x = records.reduce((result, record) => {
console.log(record)
result[record.user] = result[record.user] || []
result[record.user].push(record.time.seconds)
console.log(result)
return result
}, [])
console.log(x)
setdata(x)
}, [records])
if (!currentEvent) {
return (<h1>data loading ...</h1>)
}
return (
<Paper style={{margin: 8, padding: 8}}>
<Typography variant='h4'>
{data.length}
</Typography>
<Typography>
</Typography>
<Table >
<TableHead>
<TableRow>
<TableCell>Participant</TableCell>
<TableCell align="right">run 1</TableCell>
<TableCell align="right">run 2</TableCell>
<TableCell align="right">run 3</TableCell>
</TableRow>
</TableHead>
<TableBody>
</TableBody>
</Table>
</Paper>
)
}
/*
useEffect(() => {
console.log("hi")
console.log(records)
let data = records.reduce((result, record) => {
result[record.user] = result[record.user] || []
result[record.user].push(record.time.seconds)
console.log('coucou')
return result
}, [])
setRecords(records = 'coucou')
}, [])
*/
答案 0 :(得分:0)
您对.reduce()
函数有疑问。您将一个空数组作为初始值传递给reduce
。如果record.user
是字符串,则尝试使用字符串索引添加到数组值。这就是为什么您没有结果的原因。将第二个参数从空数组[]
更改为空对象{}