在使用react router v6版本的时候,按照之前的方法使用
src/main.tsx
是这样的,几乎不动
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import "~/assets/index.css";
import App from "~/App.tsx";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);
然后,路由
src/router/index.tsx
const router = [
{
path: "/",
element: <div>Home</div>,
},
{
path: "/about",
element: <div>About</div>,
},
];
export default router;
在APP组件 src/App.tsx
中使用路由
import "./assets/App.css";
import { Button, Divider, Flex } from "antd";
import { Link, useRoutes } from "react-router-dom";
import router from "~/router";
const App = () => {
const route = useRoutes(router);
return (
<>
<Flex gap="small" align="flex-start" vertical={false}>
<Button type="primary">
<Link to="/">首页</Link>
</Button>
<Button type="primary">
<Link to="/about">关于</Link>
</Button>
</Flex>
<Divider orientation="left">正文</Divider>
<div>{route}</div>
</>
);
};
export default App;
此时,就会报错 Uncaught Error: useRoutes() may be used only in the context of a <Router> component.
查看文档,发现需要使用一个Router包一下
无论是 BrowserRouter
还是 HashRouter
亦或是其他什么 Router
然后我修改了下APP组件
import "./assets/App.css";
import { Button, Divider, Flex } from "antd";
import { BrowserRouter, Link, useRoutes } from "react-router-dom";
import router from "~/router";
const App = () => {
const route = useRoutes(router);
return (
<BrowserRouter>
<Flex gap="small" align="flex-start" vertical={false}>
<Button type="primary">
<Link to="/">首页</Link>
</Button>
<Button type="primary">
<Link to="/about">关于</Link>
</Button>
</Flex>
<Divider orientation="left">正文</Divider>
<div>{route}</div>
<BrowserRouter/>
);
};
export default App;
但是问题还是没解决
最后发现,原来是要在最上层包
要修改 src/main.tsx
文件
import * as React from "react";
import * as ReactDOM from "react-dom/client";
import "~/assets/index.css";
import { BrowserRouter } from "react-router-dom";
import App from "~/App.tsx";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>,
);
然后后面的就不需要包了
所以APP组件就可以恢复成原来的样子
import "./assets/App.css";
import { Button, Divider, Flex } from "antd";
import { Link, useRoutes } from "react-router-dom";
import router from "~/router";
const App = () => {
const route = useRoutes(router);
return (
<>
<Flex gap="small" align="flex-start" vertical={false}>
<Button type="primary">
<Link to="/">首页</Link>
</Button>
<Button type="primary">
<Link to="/about">关于</Link>
</Button>
</Flex>
<Divider orientation="left">正文</Divider>
<div>{route}</div>
</>
);
};
export default App;
然后就不会报错了
标签:used,const,App,react,报错,context,router,import,useRoutes From: https://www.cnblogs.com/guangdelw/p/18087412