我有一个程序每 30 秒轮询一次天气,但我收到了 CORS 错误。我调查了一下,发现城市和国家被解读为未定义。
我从用户表中获取用户数据,然后通过 Axios 请求将其发送到天气 API:
return axios({
url: `https://europe-west1-hummid.cloudfunctions.net/api/weather`,
method: 'POST',
data: {
city: data?.city,
country: data?.country
},
headers: {
Authorization: `${authToken}`
},
我有,但它们以未定义的形式发送。我目前使用 useEffect 设置它以从用户表中获取数据
useEffect(() => {
const userRef = db.collection('users').doc(currentUserEmail);
userRef.get().then((doc) => {setData(toUser(doc));})
}, [currentUserEmail])
然后我将它传递给一个将其映射到接口(interface)的函数:
export interface User {
userId: string;
fname: string;
lname: string;
country: string;
city: string;
email: string;
phone: number;
}
export function toUser(doc: firebase.firestore.DocumentSnapshot): User {
return {userId: doc.id, ...doc.data()} as User;
}
有没有办法使用我的检索数据的方法或更好的方法来确保我不会得到未定义的值?另外,我未定义的原因是因为我在值上使用了可选链接吗?
最佳答案
我猜你的问题是在数据处于 data
状态之前发出 axios 请求。在发出请求之前,您需要确保状态包含从 userRef.get().then((doc) => {setData(toUser(doc));})
获取的数据。
实现这一目标的一个简单方法是将您的 axios 请求放入 useEffect
中,该请求监听 data
状态的变化,并在 data
时进行提取。 code> 不再是 undefined
或 null
:
React.useEffect(() => {
if (data) {
// Here fetch your API with data
// It won't contain any undefined
const { city, country } = data
axios({
url: `https://europe-west1-hummid.cloudfunctions.net/api/weather`,
method: 'POST',
data: {
city,
country
}
})
}
}, [data]);
查看演示:
关于javascript - firestore 中的值显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67127000/