useNavigate() 只能在 <Router> 组件的上下文中使用,但它已经在 Router 中使用

问题描述 投票:0回答:1

我需要帮助来摆脱这个错误,

useNavigate() may be used only in the context of a <Router> component.

据我的代码可以看出,

useNavigate()
是在函数
handleSubmit()
中调用的,它是在
<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;
javascript reactjs react-router router
1个回答
0
投票

不要在同一个组件中调用

useNavigate
Router
useNavigate
应该在定义
Router
的较低组件中。

只需将

<BrowserRouter>
App.js
移动到
index.js
.

像这样(index.js):

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </BrowserRouter>
);
© www.soinside.com 2019 - 2024. All rights reserved.