gpt4 book ai didi

javascript - 错误 : [PrivateRoute] is not a component. 的所有子组件必须是

转载 作者:行者123 更新时间:2023-12-05 00:23:47 33 4
gpt4 key购买 nike

我正在使用 React Router v6 并为我的应用程序创建私有(private)路由。
在文件 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 article 提出了以下解决方案由 Andrew 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>

);
}
在上面的路由中,这是私有(private)路由:
<Route exact path='/' element={<PrivateRoute/>}>
<Route exact path='/' element={<Home/>}/>
</Route>
如果授权成功,将显示该元素。否则,它将导航到登录页面。

关于javascript - 错误 : [PrivateRoute] is not a <Route> component. <Routes> 的所有子组件必须是 <Route> 或 <React.Fragment>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69864165/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com