react 使用useRoutes遇到的问题

问题一: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;

总结:在使用中我们要多发现问题,找到根本原因,多读官方文档,有助于更好的理解哦~

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值