正文从这开始~

总览

当我们尝试在react router的Router上下文外部使用useNavigate 钩子时,会产生"useNavigate() may be used only in the context of a Router component"警告。为了解决该问题,只在Router上下文中使用useNavigate 钩子。

下面是一个在index.js文件中将React应用包裹到Router中的例子。

// index.js
import {createRoot} from 'react-dom/client';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root');
const root = createRoot(rootElement); // ️ wrap App in Router root.render(
<Router>
<App />
</Router>
);

useNavigate

现在,你可以在App.js文件中使用useNavigate钩子。

// App.js
import React from 'react';
import {
useNavigate,
} from 'react-router-dom'; export default function App() {
const navigate = useNavigate(); const handleClick = () => {
// ️ navigate programmatically
navigate('/about');
}; return (
<div>
<button onClick={handleClick}>Navigate to About</button>
</div>
);
}

会发生错误是因为useNavigate钩子使用了Router组件提供的上下文,所以它必须嵌套在Router里面。

用Router组件包裹你的React应用程序的最佳位置是在你的index.js文件中,因为那是你的React应用程序的入口点。

一旦你的整个应用都被Router组件所包裹,你可以随时随地的在组件中使用react router所提供的钩子。

Jest

如果你在使用Jest测试库时遇到错误,解决办法也是一样的。你必须把使用useNavigate钩子的组件包裹在一个Router中。

// App.test.js
import {render} from '@testing-library/react';
import App from './App';
import {BrowserRouter as Router} from 'react-router-dom'; // ️ wrap component that uses useNavigate in Router test('renders react component', async () => {
render(
<Router>
<App />
</Router>,
); // your tests...
});

useNavigate钩子返回一个函数,让我们以编程方式进行路由跳转,例如在一个表单提交后。

我们传递给navigate函数的参数与<Link to="/about">组件上的to属性相同。

replace

如果你想使用相当于history.replace()的方法,请向navigate函数传递一个配置参数。

// App.js
import {useNavigate} from 'react-router-dom'; export default function App() {
const navigate = useNavigate(); const handleClick = () => {
// ️ replace set to true
navigate('/about', {replace: true});
}; return (
<div>
<button onClick={handleClick}>Navigate to About</button>
</div>
);
}

当在配置对象中将replace属性的值设置为true时,浏览器历史堆栈中的当前条目会被新的条目所替换。

换句话说,由这种方式导航到新的路由,不会在浏览器历史堆栈中推入新的条目。因此如果用户点击了回退按钮,并不会导航到上一个页面。

这是很有用的。比如说,当用户登录后,你不想让用户能够点击回退按钮,再次回到登录页面。或者说,有一个路由要重定向到另一个页面,你不想让用户点击回退按钮从而再次重定向。

你也可以使用数值调用navigate 函数,实现从历史堆栈中回退的效果。例如,navigate(-1)就相当于按下了后退按钮。

React报错之useNavigate() may be used only in context of Router的更多相关文章

  1. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  2. sqlplus 连接数据库报错SP2-0642: SQL*Plus internal error state 2130, context 0:0:0

    sqlplus 连接数据库报错SP2-0642: SQL*Plus internal error state 2130, context 0:0:0 问题描述: 使用sqlplus客户端登录数据库,报 ...

  3. 部署Maven项目到tomcat报错:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener【转】

    部署Maven项目到tomcat报错:java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderLi ...

  4. eclipse使用maven,启动工程tomcat报错:java.lang.ClassNotFoundException: org.springframework.web.context.Contex

    maven是个不错的管理jar包工具,但是我们在eclipse使用maven时,总是遇上这样那样的问题,比如今天,我编译工程,启动过后,tomcat报错:java.lang.ClassNotFound ...

  5. sqlplus连接数据库报错SP2-0642: SQL*Plus internal error state 2130, context 0:0:0解决

    sqlplus连接数据库报错SP2-0642: SQL*Plus internal error state 2130, context 0:0:0解决 sqlplus 连接数据库报错SP2-0642: ...

  6. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

  7. react报错 TypeError: Cannot read property 'setState' of undefined

    代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...

  8. React报错之Cannot find name

    正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...

  9. React报错之Cannot find namespace context

    正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...

随机推荐

  1. linux篇-linux修改网卡名(亲测有效)

    1查看网卡ip addr 2cd /etc/sysconfig/network-scripts Ls查看 3mv ifcfg-eno16777736 ifcfg-eth0重命名,然后编辑 最后一行加入 ...

  2. 深度学习与CV教程(6) | 神经网络训练技巧 (上)

    作者:韩信子@ShowMeAI 教程地址:http://www.showmeai.tech/tutorials/37 本文地址:http://www.showmeai.tech/article-det ...

  3. JavaScript Object学习笔记一

    Object.assign(target, source1, source2, ...)//用于对象的复制合并(同名属性后覆盖前)或拷贝(拷贝自身可枚举属性,不拷贝继承属性或不可枚举属性),将sour ...

  4. JuiceFS V1.0 RC1 发布,大幅优化 dump/load 命令性能, 深度用户不容错过

    各位社区的伙伴, JuiceFS v1.0 RC1 今天正式发布了!这个版本中,最值得关注的是对元数据迁移备份工具 dump/load 的优化. 这个优化需求来自于某个社区重度用户,这个用户在将亿级数 ...

  5. 《Java笔记——基础语法》

    Java笔记--基础语法       一.字符串的拼接: 例如: System.out.println(""+"");     二.换行语句: 例如: Syst ...

  6. 方法重载、方法重写、四种权限修饰、JavaBean、代码块

    方法重载(overload) 一个类中可以含有多个重名的方法. 两同一不同 ①同一个类 ②同一个方法名 ③不同参数列表:参数个数不同,参数类型不同 方法重写(override) ①子类重写的方法的修饰 ...

  7. UiPath存在图像Image Exists的介绍和使用

    一.Image Exists的介绍 检查是否在指定的UI元素中找到图像,输出的是一个布尔值 二.Image Exists在UiPath中的使用 1. 打开设计器,在设计库中新建一个Sequence,为 ...

  8. python小题目练习(三)

    题目:输出1!+2!+3!+--+10!的结果代码实现: # 定义一个函数来递归实现阶乘操作def cycle(num): if num == 1: return 1 else: return num ...

  9. Java模拟西宝高速公路

    @ 目录 写在前面 一.仿真模拟的具体要求 二.类的设计 2.1 抽象父类PubVehicles 2.2 Expressway类 2.3 Passenger类 2.4 Timer类 2.5 Displ ...

  10. Java 向数组中添加元素

    一般数组是不能添加元素的,因为他们在初始化时就已定好长度了,不能改变长度. 向数组中添加元素思路 第一步:把数组转化为集合 list = Arrays.asList(array); 第二步:向集合中添 ...