在使用react路由器时,我将导入useNavigate,v6 "react-router-dom": "^6.3.0"如下:
import { useNavigate } from 'react-router-dom';在函数中,我使用以下代码导航:
{
title: (
<FormattedMessage
id="pages.apps.cruise.channel.searchTable.subName"
defaultMessage="Rule name"
/>
),
dataIndex: 'sub_name',
render: (dom, entity) => {
return (
<a
onClick={() => {
setCurrentRow(entity);
const history = useNavigate();
history("/app/cruise/article");
}}
>
{dom}
</a>
);
},
},但是浏览器显示的错误如下:
×
TypeError: useNavigate is not a function
_jsxDEV.onClick
.ant-design-pro/src/pages/apps/cruise/channel/index.tsx:207
204 | <a
205 | onClick={() => {
206 | setCurrentRow(entity);
> 207 | const history = useNavigate();
| ^ 208 | history("/app/cruise/article");
209 | }}
210 | >
View compiled
▶ 19 stack frames were collapsed.
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error. Click the 'X' or hit ESC to dismiss this message.为什么会发生这种事?我该怎么做才能解决这个问题?我已经尝试将这段代码放在函数组件的顶部:
import { useNavigate } from 'react-router-dom';
const history = useNavigate();仍然显示如下错误:
Unhandled Rejection (TypeError): useNavigate is not a function
(anonymous function)
.ant-design-pro/src/pages/apps/cruise/channel/index.tsx:20
17 | import { SortOrder } from 'antd/lib/table/interface';
18 | import { useNavigate } from 'react-router-dom';
19 |
> 20 | const history = useNavigate();
21 |
22 | interface IChannelPageProps {
23 | channels: IChannelState
View compiled
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error. Click the 'X' or hit ESC to dismiss this message.发布于 2022-04-30 09:54:18
在调用useNavigate之前,该组件是否位于路由上下文中?如果没有,请尝试将使用useNavigate的组件与路由包装在一起:
import { Route } from 'react-router-dom';
<Route path="/yourpath" component={YourCompenent} />发布于 2022-04-30 10:02:58
我认为您应该将所有组件包装在路由器中,因为路由器在其外部不工作。尝试使用<BrowserRouter>标记:
import { BrowserRouter } from 'react-router-dom'
//then wrap all of these stuff.
<BrowserRouter>
<--Your components placed in here-->
</BrowserRouter>面对这个错误一次,希望它能帮助你解决这个问题。
https://stackoverflow.com/questions/72067116
复制相似问题