首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:当使用function路由器6时,useNavigate不是一个函数

TypeError:当使用function路由器6时,useNavigate不是一个函数
EN

Stack Overflow用户
提问于 2022-04-30 09:10:11
回答 2查看 764关注 0票数 -1

在使用react路由器时,我将导入useNavigate,v6 "react-router-dom": "^6.3.0"如下:

代码语言:javascript
复制
import { useNavigate } from 'react-router-dom';

在函数中,我使用以下代码导航:

代码语言:javascript
复制
{
      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>
        );
      },
    },

但是浏览器显示的错误如下:

代码语言:javascript
复制
×
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.

为什么会发生这种事?我该怎么做才能解决这个问题?我已经尝试将这段代码放在函数组件的顶部:

代码语言:javascript
复制
import { useNavigate } from 'react-router-dom';

const history = useNavigate();

仍然显示如下错误:

代码语言:javascript
复制
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.
EN

回答 2

Stack Overflow用户

发布于 2022-04-30 09:54:18

在调用useNavigate之前,该组件是否位于路由上下文中?如果没有,请尝试将使用useNavigate的组件与路由包装在一起:

代码语言:javascript
复制
import { Route } from 'react-router-dom';
<Route path="/yourpath" component={YourCompenent} />
票数 0
EN

Stack Overflow用户

发布于 2022-04-30 10:02:58

我认为您应该将所有组件包装在路由器中,因为路由器在其外部不工作。尝试使用<BrowserRouter>标记:

代码语言:javascript
复制
import { BrowserRouter } from 'react-router-dom'

//then wrap all of these stuff.
<BrowserRouter>
   <--Your components placed in here-->
</BrowserRouter>

面对这个错误一次,希望它能帮助你解决这个问题。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72067116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档