错误:[PrivateRouting]不是<Routing&>组件。<Routs&>的所有组件子项必须是<Routing&>或<React.Fragment&>;

Error: [PrivateRoute] is not a lt;Routegt; component. All component children of lt;Routesgt; must be a lt;Routegt; or lt;React.Fragmentgt;(错误:[PrivateRouting]不是lt;Routing组件。lt;Routs的所有组件子项必须是lt;Routing或lt;React.Fragment;)

本文介绍了错误:[PrivateRouting]不是<Routing&>组件。<Routs&>的所有组件子项必须是<Routing&>或<React.Fragment&>;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Reaction路由器V6,并且正在为我的应用程序创建专用路由。

在文件PrivateRoute.js中,我有代码

import React from 'react';
import {Route,Navigate} from "react-router-dom";
import {isauth}  from 'auth'

function PrivateRoute({ element, path }) {
  const authed = isauth() // isauth() returns true or false based on localStorage
  const ele = authed === true ? element : <Navigate to="/Home"  />;
  return <Route path={path} element={ele} />;
}

export default PrivateRoute

在文件route.js中,我写为:

 ...
<PrivateRoute exact path="/" element={<Dashboard/>}/>
<Route exact path="/home" element={<Home/>}/>

我也经历过相同的例子React-router Auth Example - StackBlitz, file App.tsx

我是不是遗漏了什么?

推荐答案

我今天遇到了同样的问题,并基于此very helpful articleAndrew Luca

提出了以下解决方案

在PrivateRoute.js中:

import React from 'react';
import { Navigate, Outlet } from 'react-router-dom';

const PrivateRoute = () => {
    const auth = null; // determine if authorized, from context or however you're doing it

    // If authorized, return an outlet that will render child elements
    // If not, return element that will navigate to login page
    return auth ? <Outlet /> : <Navigate to="/login" />;
}

在App.js中(我已经在其他一些页面中留下了示例):

import './App.css';
import React, {Fragment} from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Navbar from './components/layout/Navbar';
import Home from './components/pages/Home';
import Register from './components/auth/Register'
import Login from './components/auth/Login';
import PrivateRoute from './components/routing/PrivateRoute';

const App = () => {
  return (
    <Router>
      <Fragment>
        <Navbar/>
        <Routes>
          <Route exact path='/' element={<PrivateRoute/>}>
            <Route exact path='/' element={<Home/>}/>
          </Route>
          <Route exact path='/register' element={<Register/>}/>
          <Route exact path='/login' element={<Login/>}/>
        </Routes>
      </Fragment>
    </Router>
    
  );
}

在上述路由中,这是专用路由:

<Route exact path='/' element={<PrivateRoute/>}>
      <Route exact path='/' element={<Home/>}/>
</Route>

如果授权成功,则会显示元素。否则,它将导航到登录页面。

这篇关于错误:[PrivateRouting]不是&lt;Routing&>组件。&lt;Routs&>的所有组件子项必须是&lt;Routing&>或&lt;React.Fragment&>;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:错误:[PrivateRouting]不是&lt;Routing&>组件。&lt;Routs&>的所有组件子项必须是&lt;Routing&>或&lt;React.Fragment&>;

基础教程推荐