React報錯之useNavigate() may be used only in context of Router

2022-08-09 06:00:47

正文從這開始~

總覽

當我們嘗試在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);

//