嗨,我有带有登录页面和带有路由的主页的 React 应用程序。在这种情况下,我无法理解路径和确切路径实际上如何与反应路由器一起工作?
这是我的 App
组件代码:
const PrivateRoute = ({ component: Component , ...rest }) => {
const { userAuth, getUser } = useContext(AuthContext);
return (
<Route
{...rest}
render={props => !userAuth ? <Redirect to='/login' /> : <Component {...props} />}
/>
)
}
function App(props) {
return (
<AuthState>
<Switch>
<Route path='/login' component={SignIn} />
<PrivateRoute exact path='/' component={MainPage} /> !!! // When i switch this to path only it works fine
</Switch>
</AuthState>
);
}
export default App;
这里是 main
组件的部分代码:
<main className={classes.content}>
<div className={classes.toolbar} />
<Switch>
<Route path='/dataSets' component={DataSet} />
<Route path='/dasboard' component={Dashboardmain} />
<Redirect from='/' to='/dasboard' />
</Switch>
</main>
</div>
所以当我这样设置时:
<PrivateRoute exact path='/' component={MainPage} />
路由 /dasboard
和 dataSets
未呈现,只是更改了 URL-s
但是如果我这样设置:
<PrivateRoute path='/' component={MainPage} />
一切正常。
对理解这种行为有帮助吗?
答案 0 :(得分:3)
在你的 App.js
<Router>
<Route path="/login" component={MyLoginForm} />
<PrivateRoute path="/onlyAuthorizedAllowedHere/" component={MyComponent} />
</Router>
和 PrivateRoute 组件
import React from 'react'
import AuthService from './Services/AuthService'
import { Redirect, Route } from 'react-router-dom'
const PrivateRoute = ({ component: Component, ...rest }) => {
// Add your own authentication on the below line.
const isLoggedIn = AuthService.isLoggedIn()
return (
<Route
{...rest}
render={props =>
isLoggedIn ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: '/login', state: { from: props.location } }} />
)
}
/>
)
}
export default PrivateRoute
答案 1 :(得分:1)
exact
如果你理解它,它是一个非常有用的道具。基本可以这样理解:
当您希望用户准确地转到您想要的路线(网址)时,让我们使用 exact
。如果该路由是父路由并且有多个子路由,则不要将 exact
与父路由一起使用,而是将其用于子路由
在你的例子中我们可以这样理解
记住我们总是有一个路由父/
Login
是 /
的子节点,它不包含任何子路由 => 所以让我们为这条路由添加 exact
MainPage
也是 /
的子代,但它是 Dashboardmain
和 DataSet
的父代,所以不要为 {{ 添加 exact
1}}
/
和 Dashboardmain
是 DataSet
的孩子,但它们不包含任何子路由 => 所以让我们为它们添加 /
嵌套路由的逻辑相同。您可以使用我上面的解释创建多个嵌套路由。祝你好运!