我正在使用React Router 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,文件App.tsx
是否有什么我漏掉的东西?
<Route element={<Home/>} />
直接渲染为私有出口的子元素是更好的选择。现在这个方案更加吸引人了。我可以看到在某些使用情况下的好处。 - Drew Reeseexact
属性。 - Suroor Ahmmad