我需要帮助以消除此错误useNavigate() may be used only in the context of a <Router> component.
从我的代码中可以看出,useNavigate()
是在handleSubmit()
函数中调用的,而handleSubmit()
函数是在<form>
组件中调用的,而<form>
组件是在<Route>
组件中调用的。因此,我不明白为什么会出现此错误。有人能引导我找到解决方案吗?谢谢
我的“react-router-dom”版本是6.8.1。
import React, { useState, useEffect } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import NavBar from './NavBar';
import Footer from './Footer';
import SignIn from './SignIn';
import SignUp from './SignUp';
import TravelPlan from './TravelPlan';
function App() {
const [loggedIn, setLoggedIn] = useState(false);
const navigate = useNavigate();
const [destination, setDestination] = useState('');
const handleSubmit = async (e) => {
e.preventDefault();
const data = {
destination: destination,
};
const response = await axios.post('/travel', data);
navigate("/travelplan");
};
return (
<div>
<BrowserRouter>
<NavBar loggedIn={loggedIn} setLoggedIn={setLoggedIn} handleSignin={handleSignin} />
<Routes>
<Route path="/" element={
<div>
<form onSubmit={handleSubmit} style={{ textAlign: "center" }}>
<div>
<label>
Destination:
<input
type="text"
value={destination}
onChange={(e) => setDestination(e.target.value)}
/>
</label>
</div>
<button type="submit">Submit</button>
</form>
</div>
}>
</Route>
<Route path="/signin" element={<SignIn handleSignin={handleSignin} />} />
<Route path="/signup" element={<SignUp />} />
<Route path="/travelplan" element={<TravelPlan />} />
</Routes>
<Footer />
</BrowserRouter>
</div >
);
}
export default App;
1条答案
按热度按时间odopli941#
不要在同一个组件中调用
useNavigate
和Router
。useNavigate
应该位于定义Router
的较低组件中。只需将**
<BrowserRouter>
**从App.js
移动到index.js
即可。如下所示(index.js):