我正在从firestore获取一些数据,一切正常,但有一个很大的缺陷,我试图找出…
我只能控制台记录数据,一旦我按下"读取数据"按钮两次。有什么帮助我可以让它等待它有响应之前显示它吗?
下面是我的代码,提前感谢。
import firebase from 'firebase/compat/app'
import 'firebase/compat/firestore';
import { useState } from 'react';
export default function ReadToFirebase() {
const [data, setData] = useState([])
const readData = () => {
try {
firebase
.firestore()
.collection('users')
.onSnapshot(snapshot => {
let changes = snapshot.docChanges()
changes.forEach(change => {
let data = change.doc.data()
data = {
username: data.userName,
email: data.email
}
setData(oldArray => [...oldArray, data])
})
})
console.log('Data Read!')
console.log(data);
// return data
} catch (error) {
console.log(`Opps! Error querying data: nn ${error}`);
alert(error)
}
}
return (
<div className="p-4 grid place-items-center space-y-2">
<button onClick={readData} className="py-2 px-4 bg-gray-300 rounded-xl font-bold">Read Data</button>
<div className="">{}</div>
</div>
)
}
您的console.log
语句在onSnapshot
函数之外。如果你这样做:
const readData = () => {
try {
firebase
.firestore()
.collection('users')
.onSnapshot(snapshot => {
let changes = snapshot.docChanges()
changes.forEach(change => {
let data = change.doc.data()
data = {
username: data.userName,
email: data.email
}
setData(oldArray => [...oldArray, data])
});
console.log('Data Read!')
console.log(data);
})
// return data
} catch (error) {
console.log(`Opps! Error querying data: nn ${error}`);
alert(error)
}
}
工作。
有两点需要注意:
- 你可以用
map
代替forEach
来改进你的代码:
const changedData = changes.map(change => {
let data = change.doc.data()
return {
username: data.userName,
email: data.email
}
});
setData(oldArray => [...oldArray, ...changedData])
- 为了让
try/catch
实际捕获服务器错误,您应该将请求包装在承诺中。比如:
const readData = () => {
new Promise((resolve, reject) => {
firebase.firestore().collection('users').onSnapshot(handleSnapshot(resolve, reject)());
})
.then(handleSuccessfulUsersFetch)
.catch(handleErrorInUsersFetch);
}
还有其他方法可以实现(例如使用async/await)。你可以在这篇漂亮的文章中阅读更多关于JS中的错误处理:https://medium.com/walkme-engineering/javascript-error-handling-9fc1a2946119