简体   繁体   中英

why Passing Props in Private Route in ReactJs not working properly

Here is mycode of the file PrivateRoute.js

import React from "react";
import {Route,Redirect} from "react-router-dom"
import {isAuthenticated} from "./index"


const PrivateRoutes = (props)=>{

 return(
    isAuthenticated()?(<Route
    render={ (props) => 
      <component {...props}/>} />):
   (<Redirect to={{ pathname:"/signin"}}/>)
  //   <h1>hey there</h1>
   )
   
 }


 export default PrivateRoutes;

In this code it is saying that value of props is read but never used but iam using it in render function,destructuring is also not working here. Here isAuthenticated() is my boolean function . If it evaluates to true i want to get on more route to user dashboard.

This is how my routes.js file looks like

import React from 'react'
import {BrowserRouter,Route,Switch} from "react-router-dom";
import AdminRoutes from './auth/helper/AdminRoutes';
import PrivateRoutes from './auth/helper/PrivateRoutes';
import Home from './core/Home';
import AdminDashboard from './user/AdminDashBoard';
import Signin from './user/Signin';
import Signup from './user/Signup';
import UserDashboard from './user/UserDashBoard';


 function Routes() {
 return (
   <BrowserRouter>
  
   <Switch>
     <Route exact path='/' component={Home}  />
     <Route exact path="/signup" component={Signup} />
     <Route exact path="/signin" component={Signin} />
     <PrivateRoutes component="UserDashboard" exact path="/user/dashboard"/>
     <AdminRoutes exact path="/admin/dashboard" component={AdminDashboard}/>
   </Switch>

   </BrowserRouter>
  )
 }

 export default Routes

Help me to solve this problem.

This is because you have declared * two functions, each taking a props object argument, but only the inner/nested function's props is referenced.

Rename the nested props to something else like routeProps and spread both to the rendered component. Remember also that valid React component names are PascalCased.

Example:

const PrivateRoutes = ({ component: Component, ...props }) => {
  return isAuthenticated()
    ? (
      <Route
        render={(routeProps) => (
          <Component {...props} {...routeProps} />
        )}
      />
    ) : <Redirect to={{ pathname:"/signin"}}/>;
}

Then also fix the PrivateRoutes component use to pass a value React component reference instead of a string.

<Switch>
  <Route path="/signup" component={Signup} />
  <Route path="/signin" component={Signin} />
  <PrivateRoutes component={UserDashboard} path="/user/dashboard" />
  <AdminRoutes path="/admin/dashboard" component={AdminDashboard} />
  <Route path='/' component={Home}  />
</Switch>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM