如何在 React 路由器 v6中重定向?

我正在尝试升级到 React 路由器 v6(react-router-dom 6.0.1)。

这是我更新的代码:

import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';


<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/lab" element={<Lab />} />
<Route render={() => <Navigate to="/" />} />
</Routes>
</BrowserRouter>

最后一个 Route将其余路径重定向到 /

然而,我得到了一个错误

TS2322: 类型“{ render: () = > Element; }”不能指定为类型“ IntrinsicAttritribute & (PathRouteProps | LayoutRouteProps | IndexRouteProps)”。属性“ render”不存在于类型“ intrinsicAttritribute & (PathRouteProps | LayoutRouteProps | IndexRouteProps)”上。

然而,基于 文件,它确实有 renderRoute。我怎样才能正确地使用它?

223326 次浏览

我认为你应该使用非匹配路线的方法。

在文档中检查这一点: 添加一个“ No Match”路由

import { BrowserRouter, Navigate, Route, Routes } from 'react-router-dom';


<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/lab" element={<Lab />} />
<Route
path="*"
element={<Navigate to="/" replace />}
/>
</Routes>
</BrowserRouter>

为了保持历史记录的干净,您应该设置 replace道具。这将避免用户点击后额外的重定向。

我找到了另一种方法:

import { useNavigate } from "react-router-dom";
let navigate = useNavigate();


useEffect(() => {
if (LoggedIn){
return navigate("/");
}
},[LoggedIn]);

参见 < a href = “ https://reacrouter.com/en/v6.3.0/getting-start/view #  觀察”rel = “ noReferrer”> Overview,導航

创建文件 RequreAuth.tsx

import { useLocation, Navigate } from "react-router-dom";
import { useAuth } from "../hooks/Auth";


export function RequireAuth({ children }: { children: JSX.Element }) {
let { user } = useAuth();
let location = useLocation();


if (!user) {
return <Navigate to="/" state=\{\{ from: location }} replace />;
} else {
return children;
}
}

导入需要用户私有路由器的组件:

import { Routes as Switch, Route } from "react-router-dom";


import { RequireAuth } from "./RequireAuth";
import { SignIn } from "../pages/SignIn";
import { Dashboard } from "../pages/Dashboard";


export function Routes() {
return (
<Switch>
<Route path="/" element={<SignIn />} />
<Route
path="/dashboard"
element={
<RequireAuth>
<Dashboard />
</RequireAuth>
}
/>
</Switch>
);
}


在 React 的版本5,也就是 反应路由器中,我们使用了 Redirect 组件。但是在 React 的版本6中,它被更新为 Navigate 组件。

我们可以在这些组件中传递替换,以避免在单击后退和前进选项时出现不必要的重定向。

使用示范如下:

<Route  path="/" element={user ? <Home /> : <Register />} />
<Route path="/login" element={user ? <Navigate to="/" replace /> :  <Login />}  />
<Route path = "/register" element={user ? <Navigate to="/" replace /> :  <Register />} />
import { useState } from "react"
import { Navigate } from "react-router-dom"
const [login, setLogin] = useState(true)
return (<>
{!login && <Navigate to="/login" />}
<>)

对于类组件,首先应该创建一个函数组件,然后使用 HOC 技术来使用 useNavigate反作用钩

像这样:

文件 Withrouter.js

import {useNavigate} from 'react-router-dom';


export const withRouter = WrappedComponent => props => {
return (<WrappedComponent {...props} navigate={useNavigate()}/>);
};

然后像下面这样在其他类组件中使用它:

export default withRouter(Signin);

使用道具重定向,像这样:

this.props.navigate('/');
import { useNavigate } from "react-router-dom";
import { Button } from "@mui/material";


const component =()=>{


const navigate = useNavigate();


const handelGoToLogin = () => {
navigate('/auth/login')
}


return(<>
//.........
    

<Button onClick={handelGoToLogin} variant="outlined" color="primary" size="large" fullWidth>
Back
</Button>


</>)
}
      <BrowserRouter>
<Routes>
<Route path="/home" index element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/" element={<Navigate to="/home" replace />} />
</Routes>
</BrowserRouter>

用于反应路由器版本6

编辑后的新示例——-> (更简单易读)

import {BrowserRouter as Router,Routes,Route} from 'react-router-dom';
import Home from '../NavbarCompo/About';
import Contact from '../NavbarCompo/Contact';
import About from '../NavbarCompo/About';
import Login  from '../NavbarCompo/Login';
import Navbar from '../Navbar/Navbar';
import Error from '../pages/error';
import Products  from '../pages/products';
import Data from '../NavbarCompo/Data';


const Roter=()=>{
return (
<Router>


<Navbar />
<Routes>
            

<Route path='/' element={<Home />} />
<Route path='/about' element={<About />} />
<Route path='/contact' element={<Contact />} />
<Route path='/login' element={<Login />} />
<Route path='/product/:id' element={<Products />} />
<Route path='/data' element={<Data />} />
<Route path ='*' element={<Error />} />
</Routes>




</Router>
)
}
export default Roter;

看看这个例子

import React from "react";
import Form from "./compo/form";
import ReactDOM from "react-dom/client";
import { createBrowserRouter, RouterProvider, Route,Routes,Navigate } from "react-router-dom";


const router = createBrowserRouter([
{
path: "/",
element: <Form />
},
{
path: "/about",
element: <h1>hola amigo,you are in about section</h1>
},
{
path:"*",
element:<Navigate to="/" replace />
}
]);


const root = ReactDOM.createRoot(document.getElementById("root"));


root.render(
<React.StrictMode>
<RouterProvider router={router}></RouterProvider>
</React.StrictMode>
);

看看这个 Https://reactrouter.com/en/main/start/overview