【问题标题】:getDocs function does not work in first rungetDocs 函数在第一次运行时不起作用
【发布时间】:2021-09-11 13:14:22
【问题描述】:

当用户从 localhost:3000/ 连接时,我尝试从 Firebase 获取所有文档(它会自动重定向到 /profile),但它在第一次运行时不起作用。然后,当用户刷新页面时,它就可以工作了。我如何在第一次尝试时运行它?代码如下:

 try {
    const querySnapshot = await getDocs(collection(db, "links"));
    await querySnapshot.forEach((doc) => {
      if (stUser.uid == doc.data().uid) {
        links.push(doc.id);
      }
    });
  } catch (e) {
    console.log(e);
  }

重定向:

 function first() {
  if (!isLoggedIn.isLoggedIn) return <Redirect to="/auth" />;
     }
    function second() {
    if (isLoggedIn.isLoggedIn) return <Redirect to="/profile" />;
     }
    return (
    <div>
  <Route exact path="/">
    <Redirect to="/auth" />
   </Route>
   {handleRoute(images)}
   <Route path="/auth" component={Dashboard}>
    {second()}
   </Route>
   <Route  strict path="/profile" component={HomePage}>
    {first()}
   </Route>
 </div>
 );

【问题讨论】:

  • links 的信息如何在 UI 中呈现?您可能希望使用setStateuseState 钩子将其放入状态。查看其中一些:stackoverflow.com/…

标签: javascript reactjs firebase google-cloud-firestore


【解决方案1】:

这里的问题是你没有在你的状态下设置这个变量,正如弗兰克在 cmets 中提到的那样,所以你对这个变量所做的任何更改都可能不会被刷新,直到通过刷新页面实际强制它们。我建议您尝试以下代码:

const updatedArray = links;
await querySnapshot.forEach((doc) => {
  if (stUser.uid == doc.data().uid) {
    updatedArray.push(doc.id);
  }
});
setLinks(updatedArray);

另外,您需要在代码中更早地进行设置:

const [cars, setLinks] = useState([]);

最后,我建议您查看 documentation 以了解 useState deepdive。

【讨论】:

    猜你喜欢
    • 2012-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2023-01-08
    相关资源
    最近更新 更多