reactjs - 如何在渲染 react 应用程序之前预加载数据

我使用 React 位置库。想要从 cookie 中获取令牌(如果存在),然后将其发送到服务器以检查它是否处于活动状态。我的问题是,无论路线如何,在渲染应用程序之前我如何才能做到这一点?

我已经尝试过类似的方法,但它仅适用于特定路线

{
        path: '/',
        element: () => import('../pages/Main').then(mod => <mod.default />),
        loader: async () => {
            return {
                user: await fetchResource('user', {}, true)
            };
        }
    },

回答1

在 App.js 你可以做这样的事情

const [ready, setReady] = useState(false);
useEffect(()=>{
  // fetch your token and verify
  setReady(true)
  },[]);

return (
  {
    ready ? (
      // Your app components here
    ) : (
       <div> Loading .... </div>
    )
  }
)

相似文章

随机推荐

最新文章