Javascript firestore中显示为未定义的值

Javascript firestore中显示为未定义的值,javascript,reactjs,typescript,firebase,google-cloud-firestore,Javascript,Reactjs,Typescript,Firebase,Google Cloud Firestore,我有一个程序,每30秒对天气进行一次民意调查,结果发现CORS出现了错误。我调查了一下,发现城市和国家被解读为未定义的 我从用户表中获取用户数据,然后将其与Axios请求一起发送到weather API: return axios({ url: `https://europe-west1-hummid.cloudfunctions.net/api/weather`, method: 'POST', data: { city: data?.city,

我有一个程序,每30秒对天气进行一次民意调查,结果发现CORS出现了错误。我调查了一下,发现城市和国家被解读为未定义的

我从用户表中获取用户数据,然后将其与Axios请求一起发送到weather 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设置它,以从users表获取数据

useEffect(() => {
    const userRef = db.collection('users').doc(currentUserEmail);
    userRef.get().then((doc) => {setData(toUser(doc));})
}, [currentUserEmail])
然后我将其传递给一个函数,该函数将其映射到一个接口:

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;
}

有没有一种方法可以使用我检索数据的方法,或者有更好的方法来确保我没有得到未定义的值?另外,我之所以没有定义,是因为我在值上使用了可选的链接吗?

我想这里的问题是,在数据处于
数据状态之前,您发出了axios请求。在发出请求之前,您需要确保状态包含从
userRef.get()获取的数据。然后((doc)=>{setData(toUser(doc));})

实现这一点的一个简单方法是将axios请求置于
useffect
中,监听
数据
状态的更改,并在
数据
不再
未定义
为空时进行提取:

React.useffect(()=>{
如果(数据){
//在这里获取带有数据的API
//它不会包含任何未定义的内容
const{city,country}=数据
axios({
网址:`https://europe-west1-hummid.cloudfunctions.net/api/weather`,
方法:“POST”,
数据:{
城市
国家
}
})
}
},[数据];
签出演示: