在渲染React应用程序之前,如何预加载数据

发布于 2025-01-28 23:05:02 字数 406 浏览 3 评论 0原文

我使用React位置库。想要从cookie中获取令牌,如果存在,请将其发送到服务器以检查它是否处于活动状态。我的问题是,无论路线如何,我如何在渲染应用程序之前一次执行此操作?

我尝试过这样的事情,但仅适用于特定路线

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

i use React location library. Want to get token from cookie if it exist then send it to server to check if it is active. My question is how i can do this once before rendering app regardless of route?

i`ve tried something like this but it works only for specific route

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

电影里的梦 2025-02-04 23:05:03

在app.js中,您可以做这样的事情

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

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

In App.js you could do something like this

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

return (
  {
    ready ? (
      // Your app components here
    ) : (
       <div> Loading .... </div>
    )
  }
)
染墨丶若流云 2025-02-04 23:05:03

您可以使用此代码:

const [text, setText] = useState("")
const [loading, setLoading] = useState();
const fetchdata = () => {
  setLoading(true)
  fetch("youurl is here")
    .then((res) => res.json())
    .then((data) => setText(data.title))
  setLoading(false)
}

在组件中写下条件:

<div className='App'>
  <button onClick={fetchdata}>Fetch Data</button>
  {loading ? <p>loading</p> : <p>{text}</p>}
</div>

当然,您应该使用useeffect挂钩来获取数据

you can use this code for example:

const [text, setText] = useState("")
const [loading, setLoading] = useState();
const fetchdata = () => {
  setLoading(true)
  fetch("youurl is here")
    .then((res) => res.json())
    .then((data) => setText(data.title))
  setLoading(false)
}

and in your component write the conditional:

<div className='App'>
  <button onClick={fetchdata}>Fetch Data</button>
  {loading ? <p>loading</p> : <p>{text}</p>}
</div>

of course, you should use useEffect hook to fetch data

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文