开发者问题收集

React.js 中的路由器和重定向

2022-02-16
5987

我是 React 的初学者。 我正在尝试设置路由器和渲染以更改页面,但它给出了我无法理解的错误。

我已经安装到终端 npm install react-router-dom 在我的 index.js 中,我导入了 BrowserRouter 并嵌入了我的APP

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter} from "react-router-dom"

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);
reportWebVitals();

在我的 app.js 中,我从 react-router-dom 导入了路由开关。

import Home from './page/home';
import Authentication from "./page/authentication";
import Header from './componenti/header';
import './App.css';
import DashboardComponent from './page/dashboardComponent';
import {Route, Switch} from "react-router-dom"

function App(props) {
  return (
    <div>
      <Header/>
      <Switch>        
          <Route exact path="/" render={(props)=> <Home/>}/>
          <Route exact path="authentication" render={(props)=> <Authentication/>}/>
          <Route exact path="/dashboard-component" render={(props)=> <DashboardComponent/>}/>
      </Switch>
    </div>
  );
}
export default App;

重定向非常相似,在我的身份验证页面中,我从 react-router-dom 导入了重定向,但它不正确。

import styles from '../style/authentication.module.css';
import {useState} from "react";
import {Redirect} from "react-router-dom"

const Authentication = () => {

--- other code ---

    let postLoginRedirect = null;
    if (isLogged) {
    return postLoginRedirect = <Redirect to="/dashboardComponent"/>
    }
    return(
    <div>
    
    </div>
    )
}
export default Authentication

在我看来一切都是正确的,我阅读了很多关于这个主题的内容,我从我用react开发的web应用程序中复制了解决方案,但它不起作用,我不明白。

这是错误信息:

ERROR in ./src/App.js 18:35-41

export 'Switch' (imported as 'Switch') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)

ERROR in ./src/page/authentication.js 48:52-60

export 'Redirect' (imported as 'Redirect') was not found in 'react-router-dom' (possible exports: BrowserRouter, HashRouter, Link, MemoryRouter, NavLink, Navigate, Outlet, Route, Router, Routes, UNSAFE_LocationContext, UNSAFE_NavigationContext, UNSAFE_RouteContext, createRoutesFromChildren, createSearchParams, generatePath, matchPath, matchRoutes, renderMatches, resolvePath, unstable_HistoryRouter, useHref, useInRouterContext, useLinkClickHandler, useLocation, useMatch, useNavigate, useNavigationType, useOutlet, useOutletContext, useParams, useResolvedPath, useRoutes, useSearchParams)

3个回答

如果您使用的是 react-router-dom v6 ,则应将 Switch 替换为 Routes

import {Route, Routes } from 'react-router-dom" 
Mhammed Talhaouy
2022-02-16

几乎所有的 react-router-dom 教程都已过时,并且仍然引用 react-router-dom@5 API 规范。

看起来您意外升级/安装了最新版本的 react-router-dom ,即版本 6。您有两个选择:

  1. 降级/恢复到版本 v5.x

    卸载任何当前版本的 react-router-domreact-dom ,然后安装它们的特定 v5 版本。

    从您的项目目录运行:

    • npm un -s react-router-dom react-dom
      
    • npm i -s react-router-dom@5 react-dom@5
      
  2. 完成/应用 v5 迁移指南

    从 v5 升级

    如果您决定继续迁移,那么您可能需要卸载 react-router ,因为 react-router-dom 会重新导出 react-router 中的所有导出,或者至少您要确保它们是同一版本。

    卸载:

    npm un -s react-router
    

    或者重新安装每个的最新版本:

    • npm un -s react-router-dom react-router
      
    • npm i -s react-router-dom@latest
      

    App

    从“react-router-dom”导入{Route, Switch}
    
    function App(props) {
    return (
    <div>
    <Header />
    <Routes>
    <Route path="/" element={<Home />} />
    <Route path="authentication" element={<Authentication />} />
    <Route path="/dashboard-component" element={<DashboardComponent />} />
    </Routes>
    </div>
    );
    }
    

    身份验证

    const Authentication = () => {
    
    --- 其他代码 ---
    
    let postLoginRedirect = null;
    if (isLogged) {
    return <Navigate to="/dashboardComponent" replace />;
    }
    return(
    <div>
    ...
    </div>
    );
    }
    
Drew Reese
2022-02-16

您可以使用 React Router 中的 useNavigate 钩子。来自( 文档 ):

The useNavigate hook returns a function that lets you navigate programmatically, for example in an effect:

用法:

const navigate = useNavigate();
navigate("/somepage");
Alexandr Gotlib
2023-01-27