解決React報錯useNavigate()?may?be?used?only?in?context?of?Router
總覽
當我們嘗試在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>
);
}
會發(fā)生錯誤是因為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時,瀏覽器歷史堆棧中的當前條目會被新的條目所替換。
換句話說,由這種方式導航到新的路由,不會在瀏覽器歷史堆棧中推入新的條目。因此如果用戶點擊了回退按鈕,并不會導航到上一個頁面。
這是很有用的。比如說,當用戶登錄后,你不想讓用戶能夠點擊回退按鈕,再次回到登錄頁面?;蛘哒f,有一個路由要重定向到另一個頁面,你不想讓用戶點擊回退按鈕從而再次重定向。
你也可以使用數值調用navigate 函數,實現從歷史堆棧中回退的效果。例如,navigate(-1)就相當于按下了后退按鈕。
原文鏈接:bobbyhadz.com/blog/react-…
以上就是解決React報錯useNavigate() may be used only in context of Router的詳細內容,更多關于React報錯useNavigate的資料請關注腳本之家其它相關文章!
相關文章
關于React Native報Cannot initialize a parameter of type''NSArra
這篇文章主要介紹了關于React Native報Cannot initialize a parameter of type'NSArray<id<RCTBridgeModule>>錯誤,本文給大家分享解決方案,需要的朋友可以參考下2021-05-05
React-Native之TextInput組件的設置以及如何獲取輸入框的內容
這篇文章主要介紹了React-Native之TextInput組件的設置以及如何獲取輸入框的內容問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05
react中使用better-scroll滾動插件的實現示例
滾動在很多地方都可以使用,本文主要介紹了react中使用better-scroll滾動插件的實現示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-07-07

