组件未显示在带有 AuthProvider、React 和 Firebase 的嵌套路由器中

Component not show up in nested router with AuthProvider ,React and Firebase

我为登录用户使用 fireBase 和 PrivateRoute 进行了身份验证。 但是当我进入每个其他组件之一(不是产品登录或注册)时 URL 更新但它没有显示。 App.js

function App() {
  return (
    <AuthProvider>
        <Switch>
          <PrivateRoute exact path='/' component={MainPageComp}/>
          <Route path='/Signup' component={SignupComp}/>
          <Route path='/Login' component={LoginComp}/>
        </Switch>
      </AuthProvider>
  );
}

在 MainPageComponent 中还有路由:

<Switch>
       <PrivateRoute exact  path='/' component={ProductsComp}/>
       <Route  path='/Products' component={ProductsComp}/>
       <Route  path='/Customers' component={CustomersComp}/>
       <Route  path='/Purchases' component={PurchasesComp}/>
       <Route  path='/AddProduct' component={AddProductComp}/>
       <Route  path='/EditProduct/:id' component={EditProductComp}/>
       <Route  path='/EditCustomer/:id' component={EditCustomerComp}/>
</Switch>

PrivateRoute.js:

export default function PrivateRoute({component:Component,...rest}){

    const {currentUser} = useAuth()
    return(
        <Route
        {...rest}
        render={props=>{
          return currentUser?<Component {...props}/>:<Redirect to='/login'/>
        }}>

        </Route>
    )
}

感谢帮手

Switch 组件路径顺序和特异性很重要!您错误地指定了主 "/" 路径以使其完全匹配。这必然会排除任何 非精确 “子路由”被 PrivateRoute 匹配,并且由于路径不再完全匹配 MainPageComp 组件被卸载。

要解决,请在 Switch 中将 routes/paths 从更具体到不太具体的路径排序,并删除可能呈现 paths/routed 的任何 paths/routed 组件上的 exact 属性 nested/sub-routes 所以它们也可以被匹配和渲染。事实上,如果指定正确,你应该几乎不需要使用 exact prop.

应用程序

function App() {
  return (
    <AuthProvider>
      <Switch>
        <Route path='/Signup' component={SignupComp}/>
        <Route path='/Login' component={LoginComp}/>
        <PrivateRoute path='/' component={MainPageComp}/>
      </Switch>
    </AuthProvider>
  );
}

MainPageComp

<Switch>
  <Route  path='/Products' component={ProductsComp}/>
  <Route  path='/Customers' component={CustomersComp}/>
  <Route  path='/Purchases' component={PurchasesComp}/>
  <Route  path='/AddProduct' component={AddProductComp}/>
  <Route  path='/EditProduct/:id' component={EditProductComp}/>
  <Route  path='/EditCustomer/:id' component={EditCustomerComp}/>
  <PrivateRoute path='/' component={ProductsComp}/>
</Switch>