【问题标题】:(react router v6) "Error: useNavigate() may be used only in the context of a <Router> component" error in hoc component(反应路由器 v6)“错误:useNavigate() 只能在 <Router> 组件的上下文中使用” hoc 组件中的错误
【发布时间】:2022-06-30 11:11:10
【问题描述】:

在路由器部分,我尝试检查用户是否可以使用高阶组件 (hoc) 访问该组件。

因此,请检查用户是否在 hoc 上登录。此时,可能会阻止尝试访问每个页面或根据响应值强制移动到另一个页面。

为了移动到另一个页面,我们需要使用 hoc 组件中的“导航”方法。

但是,当使用导航方法时,会出现短语"Error: use Navigate() may be used only in the context of a &lt;Router&gt; component"

由于在路由器中使用了 hoc,我将使用 Navigate。 我想我可以做到。

你能告诉我问题是什么吗?我在这里想念什么?我是第一次尝试后端,请谅解。

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(认证)

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

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();

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    将您的 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.

    查看此链接以获得更多了解:https://dev.to/igor_bykov/react-calling-functional-components-as-functions-1d3l

    (转到标题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;
    

    【讨论】:

      【解决方案2】:

      你可以使用重定向组件:

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

      或更改位置:

      window.location.href = '/login';
      

      【讨论】:

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