简体   繁体   English

未捕获的错误:useNavigate() 只能在 a 的上下文中使用<router>零件</router>

[英]Uncaught Error: useNavigate() may be used only in the context of a <Router> component

Hello guys facing this and dont know how to solve this Tried everything to resolve this is this because of latest router library version just show you the patch of code大家好,面对这个问题,不知道如何解决这个问题尝试了一切来解决这个问题,因为最新的路由器库版本只是向您展示了代码补丁

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;

also got this error on console在控制台上也出现此错误

Uncaught Error: useNavigate() may be used only in the context of a component.未捕获的错误:useNavigate() 只能在组件的上下文中使用。 at invariant (index.tsx:19) at useNavigate (index.tsx:507) at App (App.js:23) at renderWithHooks (react-dom.development.js:14985) at mountIndeterminateComponent (react-dom.development.js:17811) at beginWork (react-dom.development.js:19049) at HTMLUnknownElement.callCallback (react-dom.development.js:3945) at Object.invokeGuardedCallbackDev (react-dom.development.js:3994) at invokeGuardedCallback (react-dom.development.js:4056)在 invariant (index.tsx:19) at useNavigate (index.tsx:507) at App (App.js:23) at renderWithHooks (react-dom.development.js:14985) at 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)

Little Help is appriciated小帮助是appriciated

Everything works fine when i remove useNavigate()当我删除 useNavigate() 时一切正常

Your <Router> needs to be higher up the component tree than where you use useNavigate , but that's not the case currently.您的<Router>需要比使用useNavigate的组件树更高,但目前情况并非如此。 You're calling useNavigate in App, but the Router is inside App, not higher up the tree from App.您在 App 中调用useNavigate ,但RouterApp 内部,而不是在 App 的树上更高。

You'll probably want to split your components up.您可能想要拆分组件。 Something like this:像这样的东西:

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>
  )
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的错误:useNavigate() 只能在<router>组件 [react-router-dom 6.4]</router> - Uncaught Error: useNavigate() may be used only in the context of a <Router> component [react-router-dom 6.4] 未捕获的错误:useNavigate() 只能在<router>成分。 - 我做错了什么?</router> - Uncaught Error: useNavigate() may be used only in the context of a <Router> component. - What is it that I am doing wrong? 未捕获的错误:useNavigate() 只能用于<Router> cypress 单元测试用例中的组件 - Uncaught Error: useNavigate() may be used only in the context of a <Router> component in cypress unit testcases useNavigate() 只能在<router>零件</router> - useNavigate() may be used only in the context of a <Router> component 错误:useNavigate() 只能在 a 的上下文中使用<router>成分</router> - Error: useNavigate() may be used only in the context of a <Router> component (反应路由器 v6)“错误:useNavigate() 只能在<router>特定组件中的组件”错误</router> - (react router v6) "Error: useNavigate() may be used only in the context of a <Router> component" error in hoc component npm 测试:useNavigate() 只能在<router>成分</router> - npm test: useNavigate() may be used only in the context of a <Router> component 未捕获的错误:useLocation() 只能在 a 的上下文中使用<router>零件</router> - Uncaught Error: useLocation() may be used only in the context of a <Router> component React Router V6 - useNavigate() 只能在一个上下文中使用<router>零件</router> - React Router V6 - useNavigate() may be used only in the context of a <Router> component 错误:useNavigate() 只能在 a 的上下文中使用<router>组件虽然我的登录页面的路由位于里面<browserrouter></browserrouter></router> - error: useNavigate() may be used only in the context of a <Router> component Although my login page's route is located inside <BrowserRouter>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM