我成功地查询了时间戳比当前日期早的Firestore文档,就像这样。
import React from 'react'
import CircularProgress from '@material-ui/core/CircularProgress'
import { useSelector } from 'react-redux'
import { useFirestoreConnect } from 'react-redux-firebase'
import Grid from '@material-ui/core/Grid'
function MeetingHistory({ userId }) {
const todaysDate = new Date()
useFirestoreConnect([
{ collection: 'users',
doc: userId,
subcollections: [{ collection: 'scheduled',
where: [
['date', '<', todaysDate],
]
}],
storeAs: `${userId}-history-scheduled`
}
])
const pastMeetings = useSelector(state => state.firestore.ordered[`${userId}-history-scheduled`])
if (!pastMeetings) return (
<Grid container direction='row' alignItems='center' justify='center'>
<CircularProgress />
</Grid>
)
console.log('meetings', pastMeetings)
return (
<div>
<p>I am going to render past meeting data here</p>
</div>
)
}
export default MeetingHistory
但是.., console.log('meetings', pastMeetings)
正在不断地打印,这让我相信,由于当前的日期随着时间的流逝而不断更新,我的数据库每秒钟都会被查询。看到new Date()在不断变化,这是有道理的,但我不希望出现这种行为。我正在寻找一种方法来获取一个不会随着时间变化而不断变化的时间快照,并以此为基础进行查询。任何解决这个问题的方法都将是非常感激的。我的目标仅仅是避免随着时间的推移而频繁查询。
我怀疑是否有人好奇,但如果他们是什么工作。使用常规的Firestore查询。
const todaysDate = new Date()
const [pastMeetings, setPastMeetings] = useState(null)
useEffect(() => {
const db = firebase.firestore()
db.collection('users').doc(userId).collection('scheduled').where('date', '<=', todaysDate).limit(15)
.get()
.then(snap => {
var temp = []
snap.forEach(doc => {
temp.push(doc.data())
})
setPastMeetings(temp)
})
.catch(err => {
console.log('error', err)
})
}, [userId])
if (!pastMeetings) return (
<Grid container direction='row' alignItems='center' justify='center'>
<CircularProgress />
</Grid>
)
console.log('meetings', pastMeetings)
这就像预期的那样运行一次。我想一定是我使用FirestoreConnect时出现了问题,或者是redux-firestore出现了问题。另外,我当然要在useEffect()里面运行,因为在查询中更新状态会导致无限次的重新渲染。我不能在useEffect()里面调用useFirestoreConnect,因为你不能在回调里面使用钩子。