问题一:Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
这个是在写路由表的时候,element尝试使用了()=>{import "xxx"}方法,报的错。在这里,element只能是一个React.ReactNode。
我们仔细阅读源码,就能知道useRoutes接收的第一个参数是一个 数组 (RouteObject[]),而数组中的RouteObject 必须包含以下参数:
问题二:React Hook "useRoutes" cannot be called at the top level. React Hooks must be called in a React function component or a custom React Hook function.eslintreact-hooks/rules-of-hooks.
这个错的意思是React Hook "useRoutes" 不能在顶层调用。 React Hooks 必须在 React 函数组件或自定义 React Hook 函数中调用。
错误写法:
import { useRoutes, Navigate } from "react-router-dom";
import Main from "../pages/main";
import Home from "../pages/home/home";
import Gh from "../pages/gh/gh";
const routes = useRoutes([
{
path: "/",
element: <Navigate to="/main/home" />,
},
{
path: "/main",
element: <Main />,
children: [
{
path: "gh",
element: <Gh />,
},
{
path: "home",
element: <Home />,
},
],
},
]);
export default routes;
在这里 直接使用了useRoutes,外层也没有任何函数包裹。useRoutes是React Hook那么就要遵守Hook的调用规则。那么我们就来看看React Hook的使用规则。Hook 规则 – Reacthttps://zh-hans.reactjs.org/docs/hooks-rules.html
我们可以看到,只能在react函数中调用。既然找到了错误,那么正确的写法就来啦
import { useRoutes, Navigate } from "react-router-dom";
import Main from "../pages/main";
import Home from "../pages/home/home";
import Gh from "../pages/gh/gh";
const Routes = () => {
const routes = useRoutes([
{
path: "/",
element: <Navigate to="/main/home" />,
},
{
path: "/main",
element: <Main />,
children: [
{
path: "gh",
element: <Gh />,
},
{
path: "home",
element: <Home />,
},
],
},
]);
return routes;
};
export default Routes;
总结:在使用中我们要多发现问题,找到根本原因,多读官方文档,有助于更好的理解哦~