【问题标题】:Component not show up in nested router with AuthProvider ,React and Firebase组件未显示在具有 AuthProvider、React 和 Firebase 的嵌套路由器中
【发布时间】:2022-01-13 19:01:21
【问题描述】:

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

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

在MainPageComponent中也有Routes:

<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>
    )
}

感谢大家的帮助

【问题讨论】:

    标签: reactjs firebase-authentication react-router-dom


    【解决方案1】:

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

    要解决此问题,请将 Switch 中的路由/路径从更具体到不太具体的路径排序,并删除任何可能呈现嵌套/子路由的路径/路由组件上的 exact 属性,以便它们也可以匹配并渲染。事实上,如果指定正确,您应该几乎零需要使用 exact 属性。

    应用程序

    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>
    

    【讨论】:

      猜你喜欢
      • 2014-11-24
      • 2020-12-22
      • 2021-05-19
      • 1970-01-01
      • 2021-10-09
      • 2016-10-10
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      相关资源
      最近更新 更多