包版本:
问题: 今天用vite+react+ts重新搭建项目时报错
代码:
router.tsx
import { useRoutes } from 'react-router-dom'; import Home from "../pages/home/index";const routers=[{path: '/',element: <Home/> } ] // const Router export const Router = useRoutes(routers);
app.tsx
import React from 'react' import './App.css' import {BrowserRouter} from "react-router-dom"; import {Router} from "./config/router";function App() {return (<div><BrowserRouter ><Router/></BrowserRouter></div>) }export default App
原因:
hooks只能在组件体或者函数体内使用
参考:useRouter() throws "Invalid hook call" when extending React.Component · Issue #8244 · vercel/next.js · GitHub
解决:
router.tsx
import { useRoutes } from 'react-router-dom'; import Home from "../pages/home/index";const routers=[{path: '/',element: <Home/> } ] // const Router export const Router = ()=>useRoutes(routers);
ps: 基础不牢 地动山摇~ 多看文档~ 😂😂