反应路线中的确切路径无法按预期工作

React exact path in Route doesnt work as expected

您好,我有带有登录页面和带有路由的主页的 React 应用程序。在这种情况下,我无法理解路径和确切路径实际上是如何与 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} />

路由/dasboarddataSets没有渲染,只是改变了URL-s

但是如果我这样设置:

<PrivateRoute path='/' component={MainPage} />

一切正常。

对理解这种行为有什么帮助吗?

像这样在你的 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

exact 是一个非常有用的道具,如果你理解的话。基本可以这样理解:

Let's use exact when you want user to go to exactly route (url) you want. If that route is a parent route and it has multiple child routes, don't use exact with the parent route, use it for children routes instead

在你的例子中我们可以这样理解

  1. 记住我们总是有一个父路由/

  2. Login/ 的子路由,它不包含任何子路由 => 所以让我们为这条路由添加 exact

  3. MainPage 也是 / 的子代,但它是 DashboardmainDataSet 的父代,所以不要添加 exact /

  4. DashboardmainDataSet/ 的子路由,但它们不包含任何子路由 => 所以让我们为它们添加 exact

与嵌套路由相同的逻辑。您可以根据我上面的解释创建多个嵌套路由。祝你好运!