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

iswrvxsc  于 2023-03-06  发布在  Java
关注(0)|答案(1)|浏览(203)

我需要帮助以消除此错误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;
odopli94

odopli941#

不要在同一个组件中调用useNavigateRouteruseNavigate应该位于定义Router的较低组件中。
只需将**<BrowserRouter>**从App.js移动到index.js即可。

如下所示(index.js):

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </BrowserRouter>
);

相关问题