简体   繁体   English

(反应路由器 v6)“错误:useNavigate() 只能在<router>特定组件中的组件”错误</router>

[英](react router v6) "Error: useNavigate() may be used only in the context of a <Router> component" error in hoc component

In the Router section, I try to check whether the user has access to the component using the higher order component (hoc).在路由器部分,我尝试检查用户是否可以使用高阶组件 (hoc) 访问该组件。

Therefore, check whether the user is logged in at the hoc.因此,请检查用户是否在 hoc 上登录。 At this time, an attempt to access each page may be prevented or forced to move to another page according to the response value.此时,可以根据响应值阻止或强制移动到另一个页面来访问每个页面的尝试。

In order to move to another page, we need to use the "navigate" method in the hoc component.为了移动到另一个页面,我们需要使用 hoc 组件中的“导航”方法。

However, when using the navigate method, the phrase "Error: use Navigate() may be used only in the context of a <Router> component" appears.但是,当使用导航方法时,会出现短语"Error: use Navigate() may be used only in the context of a <Router> component"

Since hoc is used in the router, I'm going to use Navigate.由于在路由器中使用了 hoc,我将使用 Navigate。 I think I can do it.我想我能做到。

Can you tell me what the problem is?你能告诉我问题是什么吗? What am I missing here?我在这里想念什么? It's my first time trying the backend, so please understand.这是我第一次尝试后端,所以请理解。

src/App.js src/App.js

import './App.css';
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Link
} from "react-router-dom";
import LandingPage from "./components/views/LandingPage/LandingPage";
import LoginPage from "./components/views/LoginPage/LoginPage";
import RegisterPage from "./components/views/RegisterPage/RegisterPage";
import Auth from "./hoc/auth"; //<-- this is hoc!!!!!!!!!!!!!!

function App() {
  return (
    <Router>
      <div>
        <Routes>
          <Route path="/" element={Auth(LandingPage, null)}/>
          <Route path="/login" element={Auth(LoginPage, false)}/>
          <Route path="/register" element={Auth(RegisterPage, false)}/>
        </Routes>
      </div>
    </Router>
  );
}
export default App;

src/hoc/auth.js (Auth) src/hoc/auth.js (认证)

import React, { useEffect } from "react";
import axios from "axios";
import {useDispatch} from "react-redux";
import {auth} from "../_actions/user_action";
import { useNavigate } from "react-router-dom";

export default function(SpecificComponent, option, adminRoute = null){
    
    function AuthenticationCheck(props){
        let navigate = useNavigate(); //<-- this doesn't work!!!!
        const dispatch = useDispatch();
        
        useEffect(()=> {
            dispatch(auth()).then(response => {
                console.log(response);
                
                if(!response.payload.isAuth){
                    if(option){
                        navigate('/login');//<-- this doesn't work!!!!
                    }
                } else {
                    if(adminRoute && !response.payload.isAdmin){navigate('/')} 
                    else { 
                        if(option === false){ navigate('/'); //<-- this doesn't work!!!!}
                    }
                }
            })
        },[])
        return (
        <SpecificComponent/>
        )
    }
    
    return AuthenticationCheck();
}

index.js index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import "antd/dist/antd.css";
import {Provider} from "react-redux";
import {applyMiddleware, createStore} from "redux";
import promiseMiddleware from "redux-promise";
import ReduxThunk from "redux-thunk";
import Reducer from "./_reducers";

const createStoreWithMiddleware = applyMiddleware(promiseMiddleware, ReduxThunk)(createStore);


ReactDOM.render(
    <Provider store={createStoreWithMiddleware(Reducer,
            window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
        )}>
        <App />
    </Provider>,
  document.getElementById('root')
);

reportWebVitals();

Update your HOC as将您的 HOC 更新为

Note: Calling a component as Function rather than JSX Element may lead to unexpected bugs and also creates issues with the usage of Hooks.

Check out this link for more understanding about Calling as Component vs Calling As Function : https://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l查看此链接以进一步了解Calling as Component vs Calling As Functionhttps://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l

(Goto heading What is a Component at all? ) (转到标题What is a Component at all?

import {BrowserRouter, Routes, Route, useNavigate} from "react-router-dom";

function ActualComp(navigate){
  console.log(navigate)
  return <>Actual Comp</>
}

function HOC(SpecificComponent, option, adminRoute = null){
    
    function AuthenticationCheck(props){
        let navigate = useNavigate(); 
        return (
              <SpecificComponent navigate={navigate} />
        )
    }
    
    return <AuthenticationCheck />; <---- Here instead of `AuthenticationCheck()`
}

function App() {
  return (
    <div>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={HOC(ActualComp)} />
        </Routes>
      </BrowserRouter>
    </div>
  );
}

export default App;

You can use Redirect component:您可以使用重定向组件:

import { Redirect, useHistory} from 'react-router-dom';
...

const history = useHistory();
<Redirect
    to={{
        pathname: '/login',
        state: { from: history.location },
    }}
/>

or change location:或更改位置:

window.location.href = '/login';

暂无
暂无

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

相关问题 React js:错误:useLocation()只能在a的上下文中使用<router>成分</router> - React js: Error: useLocation() 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> 未捕获的错误:useLocation() 只能在 a 的上下文中使用<router>零件</router> - Uncaught Error: useLocation() may be used only in the context of a <Router> component React - react-router v6 在类组件中使用 Navigate 并设置状态 - React - react-router v6 useNavigate in class component and set state 我如何解析“ useHref() 只能在上下文中使用<router>组件”当组件已经在里面时<router> ?</router></router> - How can I resolver " useHref() may be used only in the context of a <Router> component" when component is already inside <Router>? 反应路由器v4错误链接组件 - react router v4 error Link component react router v6 useNavigate vs Navigate location 实现 - react router v6 useNavigate vs Navigate location implementation react-router-dom v6历史推送和useNavigate问题 - react-router-dom v6 history push and useNavigate problem React Router Dom,使用 useNavigate 将数据传递给组件 - React Router Dom, pass data to a component with useNavigate 使用 react-router v6 和 useNavigate 动态生成查询参数 - Dynamically generating query params with react-router v6 and useNavigate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM