【问题标题】:Values from firestore showing as undefinedfirestore 中的值显示为未定义
【发布时间】:2021-07-11 14:01:48
【问题描述】:

我有一个程序每 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 设置它以从 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;
}

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

【问题讨论】:

    标签: javascript reactjs typescript firebase google-cloud-firestore


    【解决方案1】:

    我猜你的问题是你在data 状态下有数据之前提出了你的 axios 请求。在发出请求之前,您需要确保状态包含从userRef.get().then((doc) => {setData(toUser(doc));}) 获取的数据。

    实现此目的的一种简单方法是将您的 axios 请求置于 useEffect 中,以侦听 data 状态的变化,并在 data 不再是 undefinednull 时进行提取:

      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]);
    

    查看演示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多