我正在尝试在我的个人网站中添加预加载器。问题是无法让它发挥作用, 正如你在图片中看到的 [1]: 我尝试在路由器之前渲染它,以便它在其他任何东西之前运行。 代码很简单
const [screenLoading, setScreenLoading] = useState(false);
useEffect(() => {
setScreenLoading(true);
setTimeout(() => {
setScreenLoading(false);
}, 1000);
}, []);
一秒后状态将变为 false 并且站点将加载。但我收到此错误“警告:无效的挂钩调用。挂钩只能在函数组件的主体内部调用。”这是有道理的,但我没有任何返回函数来运行里面的代码。
import React from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import { useState, useEffect } from 'react';
//contexts
// import { MousePos } from './mousePosContext';
//components
import Header from './Header'
// import Footer from './Footer'
import ErrorPage from "./error-page";
//pages
import Home from './Home'
import Profile from "./Profile"
import Works from "./Works"
import Blogs from "./Blogs"
import Wm from "./works/web-monitization"
import Ss from "./works/scheduling-system"
import Bs from "./works/bharatSteel"
import Load from "./loader"
const [screenLoading, setScreenLoading] = useState(false);
useEffect(() => {
setScreenLoading(true);
setTimeout(() => {
setScreenLoading(false);
}, 1000);
}, []);
const router = createBrowserRouter([
{
path: "/",
element: <Header />,
errorElement: <ErrorPage />,
children: [
{
path: "",
element: <Home />,
index: true,
loader: async () => {
console.log("router loader called")
const test = (x) => {
console.log(x)
}
return test
}
},
{
path: "/profile",
element: <Profile />,
},
{
path: "/works",
element: <Works />,
},
{
path: "/works/web-monetization",
element: <Wm />
},
{
path: "works/input-validaton",
element: <Wm />
},
{
path: "works/scheduling-system",
element: <Ss proji="scheduling-system" />
},
{
path: "works/bharat-steel",
element: <Bs proji="scheduling-system" />
},
{
path: "blogs",
element: <Blogs />
},
{
path: "loader",
element: <Load />
}
]
}
]);
ReactDOM.createRoot(document.getElementById('root')).render(
<div className='layout'>
{screenLoading? <Load /> :
<RouterProvider router={router} />}
</div>
)
那么有人可以告诉我如何实现它吗?如果有其他方法可以使用React Router实现预加载器,则加载器需要在每次站点首次加载时运行,而不管正在加载哪个页面。
谢谢你。
问题与react-router这一行无关
const [screenLoading, setScreenLoading] = useState(false);
它是无效的,你不能在组件体之外使用
useState
。与useEffect
相同
创建一个组件来解决这个问题:
const Wrapper = () => {
const [screenLoading, setScreenLoading] = useState(false);
useEffect(() => {
setScreenLoading(true);
setTimeout(() => {
setScreenLoading(false);
}, 1000);
}, []);
return <div className='layout'>
{screenLoading? <Load /> :
<RouterProvider router={router} />}
</div>
}
ReactDOM.createRoot(document.getElementById('root')).render(<Wrapper />)