javascript - firestore 中的值显示为未定义

标签 javascript reactjs typescript firebase google-cloud-firestore

我有一个程序每 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> 不再是 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]);

查看演示:

Edit goofy-neumann-gvup0

关于javascript - firestore 中的值显示为未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67127000/

相关文章:

javascript - 在 React js 中使用 Reactstrap 从多个选择下拉列表中动态选择选项

javascript - 动态要求和取消要求文件

reactjs - MongoDB - 语法错误 : Invalid regular expression in $regex

javascript - VSCode 在导入自动完成时添加 .js 扩展名

Angular 2 - 重定向到外部 URL 并在新选项卡中打开

angular - 不满足条件时取消 Observable 中链

php - 在单个文件中提供 CSS 和 JS,可能的优点和缺点

javascript - 每张图片都比前一张JS少

javascript - Node.js:从请求中获取路径

javascript - 在 Widget、jQuery Datepicker 中将 DateFormat 更改为欧洲(问题!)