【问题标题】:Uncaught Error: useNavigate() may be used only in the context of a <Router> component未捕获的错误:useNavigate() 只能在 <Router> 组件的上下文中使用
【发布时间】:2022-01-11 05:53:03
【问题描述】:

大家好,遇到这个问题,不知道如何解决 想尽一切办法解决这个问题 这是因为最新的路由器库版本 只是给你看代码补丁

import "./App.css";
import Form from "./Form";
import {
  BrowserRouter as Router,
  Routes,
  Route,
  useNavigate,
  
} from "react-router-dom";
import { useEffect, useState } from "react";
import { app } from "./firebase-config";
import {
  getAuth,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
} from "firebase/auth";
import Home from "./Home";

function App() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const[data,setData]=useState({});
    let navigate = useNavigate();

  useEffect(() => {
    let authToken = sessionStorage.getItem("Auth Token");

    // if (authToken) {
    //   // navigate("/home");
    //   window.location.href = "/home";
    console.log(data);
    // }
  }, []);
  const handleAction = (id) => {

    console.log(id);
    const authentication = getAuth();
    if (id === 2) {
      createUserWithEmailAndPassword(authentication, email, password).then(
        (response) => {
          sessionStorage.setItem(
            "Auth Token",
            response._tokenResponse.refreshToken
          );
          setData(response._tokenResponse);
           navigate('/home');
          window.location.href = "/home";

          console.log(response);
        }
      );
    } else if (id === 1) {
      console.log("response");

      signInWithEmailAndPassword(authentication, email, password).then(
        (response) => {
          console.log(response);
          setData(response._tokenResponse);

          sessionStorage.setItem(
            "Auth Token",
            response._tokenResponse.refreshToken
          );
           navigate("/home");
          // window.location.href = "/home";
        }
      );
    }
  };
  return (
    <Router>
      <div className="App">
        <>
          <Routes>
            <Route
              path="/login"
              element={
                <Form
                  title="Login"
                  setEmail={setEmail}
                  setPassword={setPassword}
                  handleAction={() => handleAction(1)}
                  data={data}
                />
              }
            />
            <Route
              path="/register"
              element={
                <Form
                  title="Register"
                  setEmail={setEmail}
                  setPassword={setPassword}
                  handleAction={() => handleAction(2)}
                  data={data}
                />
              }
            />
            <button onClick={() => navigate(-1)}>go back</button>

            <Route path="/home" element={<Home data={data} />} />
          </Routes>
        </>
      </div>
    </Router>
  );
}

export default App;

在控制台上也出现此错误

未捕获的错误:useNavigate() 只能在 a 的上下文中使用 零件。 不变(index.tsx:19) 在 useNavigate (index.tsx:507) 在应用程序 (App.js:23) 在 renderWithHooks (react-dom.development.js:14985) 在 mountIndeterminateComponent (react-dom.development.js:17811) 在 beginWork (react-dom.development.js:19049) 在 HTMLUnknownElement.callCallback (react-dom.development.js:3945) 在 Object.invokeGuardedCallbackDev (react-dom.development.js:3994) 在 invokeGuardedCallback (react-dom.development.js:4056)

有一点帮助

当我删除 useNavigate() 时一切正常

【问题讨论】:

    标签: reactjs react-router react-router-dom


    【解决方案1】:

    您的&lt;Router&gt; 需要比您使用useNavigate 的位置更高,但目前情况并非如此。您在 App 中调用 useNavigate,但 Router在 App 内部,而不是在 App 的树上更高。

    您可能希望拆分组件。像这样的:

    function App() {
      return (
        <Router>
          <SomeOtherComponent/>
        </Router>
      )
    }
    
    function SomeOtherComponent() {
      const [email, setEmail] = useState("");
      const [password, setPassword] = useState("");
      const [data,setData] = useState({});
      let navigate = useNavigate();
    
      // ... etc. Code is exactly the same as yours, just no Router in the return
    
      return (
        <div className="App">
          <>
            <Routes>
              // etc
            </Routes>
          </>
        </div>
      )
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 2022-11-15
      • 2021-12-25
      • 2022-06-30
      • 2021-01-31
      • 1970-01-01
      • 2021-04-02
      相关资源
      最近更新 更多