I am following this tutorial to implement Nested routing.
Here's the relevant code:
App.js
<PrivateRoute
exact
name="Home"
path="/home"
component={DefaultLayout}
/>
DefaultLayout.js
const Users = React.lazy(() => import("../../views/Users/Users"));
<Route path="/home/users" component={Users} />
PrivateRoute.js
import React from "react";
import { Route, Redirect } from "react-router-dom";
import { connect } from "react-redux";
import PropTypes from "prop-types";
const PrivateRoute = ({ component: Component, auth, ...rest }) => (
<Route
{...rest}
render={props =>
auth.isAuthenticated === true ? (
<Component {...props} />
) : (
<Redirect to="/" />
)
}
/>
);
PrivateRoute.propTypes = {
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(mapStateToProps)(PrivateRoute);
So as you may have guessed, I am protecting the /home route with the PrivateRoute component.
The /home routes is associated with DefaultLayout component.
The DefaultLayout component contains a NestedRoute that is /home/users which leads to the component Users .
The private route functions properly and it routes the user after he logs-in to the default layout:
However when I click on a button that routes me to /home/users , I get this blank screen:
Any idea what I've done wrong?
EDIT 1 : When I add this to App.js:
const Users = React.lazy(() => import("../../views/Users/Users"));
<Route path="/home/users" component={Users} />
I do get routed to the Users component. However, not as a nested route but as a component in the root routes . In other words, the Users component does not appear inside the defaultLayout component but appears as a root component . I hope that makes sense. Here's a screenshot:
EDIT 1 Conclusion: The Nested routing implementation doesn't work. The app still routes from inside App.js instead from inside DefaultLayout.js .
EDIT 2: I realized that even without the PrivateRoute component and using the normal Route component, the nested routing still doesn't work:
<Route exact path="/home" name="Home" component={DefaultLayout} />
Looks like you need to remove the exact
prop from your Home
Route
:
<Route path="/home" name="Home" component={DefaultLayout} />
With exact
, your DefaultLayout
component will only be rendered when the url is exactly /home
. Since /home/users
isn't equal to /home
, when you navigate to /home/users
, neither your DefaultLayout
component nor the nested Users
route will be rendered.
Here are the docs that describe the exact
prop: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Route.md#exact-bool
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.