我在应用程序中使用路由时遇到了一些问题.js

<GuestRoute path="/Authenticate" element={<Authenticate />}>
</GuestRoute>

它可以和你一起工作

<Route path="/Authenticate" element={<Authenticate />}>
</Route>

但我得用客房

App.js

import "./App.css";
import {BrowserRouter as Router, Routes, Route,   Navigate } from "react-router-dom";
import React from "react"
import Navigation from "./components/shared/Navigation/Navigation";
import Home from "./Pages/Home/Home";
import Register from "./Pages/Register/Register";
import Login from "./Pages/Login/Login";
import Authenticate from "./Pages/Authenticate/Authenticate";

const isAuth = true;


function App() {
  return (
    <div className="App">
     

      <Router>
            <Navigation /> 

            {/* switch(prev. versions) ----> Routes (new versions)) */}
            <Routes>                   

                <Route exact path="/" element={<Home />} >
                </Route>
                <GuestRoute path="/Authenticate" element={<Authenticate />}>
                </GuestRoute>
                
            </Routes>

      </Router> 

    </div>
  );
}

const GuestRoute = ({children,...rest}) => {
  return(
    <Route {...rest}
    render={({location})=>{
      return isAuth ? (
       <Navigate to={{
           pathname: '/rooms',
           state: {from: location}
         }}
        />
      ):(
        children
      );
    }}
    ></Route>
  );
};

  
export default App;

推荐答案

react-router-dom@6不使用自定义管线组件.v6中使用的新模式是包装器组件或布局布线组件.

包装器组件示例:

const GuestWrapper = ({ children }) => {
  ... guest route wrapper logic ...

  return (
    ...
    {children}
    ...
  );
};

...

<Router>
  <Navigation /> 

  <Routes>                   
    <Route path="/" element={<Home />} />
    <Route
      path="/Authenticate"
      element={(
        <GuestWrapper>
          <Authenticate />
        </GuestWrapper>
      )}
    />
  </Routes>
</Router>

布局管线组件示例:

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

const GuestLayout = () => {
  ... guest route wrapper logic ...

  return (
    ...
    <Outlet /> // <-- nested routes render here
    ...
  );
};

...

<Router>
  <Navigation /> 

  <Routes>                   
    <Route path="/" element={<Home />} />
    <Route element={<GuestLayout>}>
      <Route path="/Authenticate" element={<Authenticate />} />
      ... other GuestRoute routes ...
    </Route>
  </Routes>
</Router>

Javascript相关问答推荐

从PWA中的内部存储读取文件

单击子元素时关闭父元素(JS)

我可以从React中的出口从主布局调用一个处理程序函数吗?

使用useEffect,axios和useParams进行react测试

阿波罗返回的数据错误,但在网络判断器中是正确的

如何在不影响隐式类型的情况下将类型分配给对象?

Nextjs 13.4 Next-Auth 4.2登录(&Quot;凭据&,{});不工作

有效路径同时显示有效路径组件和不存在的路径组件

在表单集中保存更改时删除';禁用';

Django导入问题,无法导入我的应用程序,但我已在设置中安装了它

构建器模式与参数对象输入

如何在AG-Grid文本字段中创建占位符

JavaScript -复制到剪贴板在Windows计算机上无效

在JavaScript中,有没有一种方法可以迭代字符串的词法标记?

如何在TransformControls模式下只保留箭头进行翻译?

P5play SecurityError:无法从';窗口';读取命名属性';Add';:阻止具有源的帧访问跨源帧

如何在Firebase中读取对象的特定字段?

Firebase函数中的FireStore WHERE子句无法执行

使用重新 Select 和对象理解 Select 器备忘

JS:inline date子串.