我想从react-router-dom
使用useNavigation()
,但得到以下错误:
Error: useNavigation must be used within a data router.
See https://reactrouter.com/en/main/routers/picking-a-router.
NavBar
src/components/NavBar.js:6
3 | import { useNavigation } from "react-router-dom";
4 |
5 | function NavBar() {
> 6 | const navigate = useNavigation();
7 | const handleClick = (e) => {
8 | navigate("/login");
9 | };
但是我用BrowserRouter
Package 了我的整个应用程序,如下所示:
import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter as Router } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<Router>
<App />
</Router>
</React.StrictMode>
);
我也使用如下路线:
import SideMenu from "./components/SideMenu";
import Content from "./components/Content";
import Projects from "./pages/Projects";
import { Routes, Route } from "react-router-dom";
function App() {
return (
<div className="App">
<Routes>
<Route exact path="/" element={<div>Home</div>} />
<Route path="/login" element={<Login />} />
<Route path="/signin" element={<SignUp />} />
<Route path="/projects" element={<Projects />} />
<Route
path="/main"
element={
<Main
nav={<NavBar />}
sideMenu={<SideMenu />}
content={<Content />}
/>
}
/>
</Routes>
</div>
);
}
我的NavBar组件看起来像这样:
import React from "react";
import "./NavBar.css";
import { useNavigation } from "react-router-dom";
function NavBar() {
const navigate = useNavigation();
const handleClick = (e) => {
navigate("/login");
};
return (
<div className="navbar">
<ul className="nav-list">
<li className="nav-item">
<button className="nav-login" onClick={handleClick}>
Login
</button>
</li>
</ul>
</div>
);
}
所以最后,我的NavBar
组件在BrowserRouter
内,但根据错误,我理解情况并非如此。有没有人有解决这个问题的办法?
2条答案
按热度按时间u2nhd7ah1#
useNavigation
钩子是仅限数据路由器的钩子。您使用的不是数据路由器,而是常规的BrowserRouter
。换句话说,您直接使用BrowserRouter
,而不是createBrowserRouter
创建的BrowserRouter
。useNavigation
此功能仅在使用数据路由器时有效,请参阅Picking a Router
既然你想发出命令式的导航操作,那么就使用
useNavigate
钩子。useNavigate
useNavigate
钩子返回一个函数,该函数允许您以编程方式进行导航hmmo2u0o2#
注意:
将失败,并出现此错误,此时您可能需要: