反应PrivateRoute无法正确呈现子级

时间:2020-09-11 16:59:37

标签: reactjs react-router-v4

Link to sandbox 当我使用PrivateRoute时,DOM呈现<children history="[object Object]" location="[object Object]" match="[object Object]"></children>而不是我传递的<AdminLayout/>的{​​{1}}。

不确定我要去哪里。 screenshot of dom

AppRouter中的错误:未定义子级

这:

PrivateRoute

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

这是Check the render method of `Context.Consumer`.

PrivateRoute

这是import React from "react"; import { Route, Redirect } from "react-router-dom"; function PrivateRoute({ children, roles, ...rest }) { console.log("childen", children); return ( <Route {...rest} render={(props) => { console.log("propsssss", props); // if (!localStorage.getItem('userid')) { if (!localStorage.getItem("access_token")) { // not logged in so redirect to login page with the return url return ( <Redirect to={{ pathname: "/auth/login", state: { from: props.location } }} /> ); } // logged in so return component return <children {...props}/>; }} /> ); } export default PrivateRoute;

AppRouter

这是import React from "react"; import { Router, Route, Switch, Redirect } from "react-router-dom"; import history from "../helpers/history"; import AdminLayout from "layouts/Admin/Admin.js"; import AuthLayout from "layouts/Auth/Auth.js"; import PrivateRoute from "./PrivateRoute"; const AppRouter = () => { return ( <Router history={history}> <PrivateRoute path="/admin" render={(props) => <AdminLayout {...props} />} /> <Route path="/auth/login" render={(props) => <AuthLayout {...props} />} /> <Redirect from="*" to="/auth/login" /> </Switch> </Router> ); }; export default AppRouter;

history.js

1 个答案:

答案 0 :(得分:2)

代码中存在两个问题,一个是您正在使用var navigationStrategy = new BottomBarNavicationStrategy(this); bottomNavigationBar.NavigationItemSelected += OnItemSelected; void OnItemSelected(object sender, BottomNavigationView.NavigationItemSelectedEventArgs e) { navigationStrategy.Navigate(this, e.Item.ItemId); } 来生成组件,而在renderProps组件中却希望自己是孩子。正确的方法:

PrivateRoute

<PrivateRoute path="/admin"> <AdminLayout /> </PrivateRoute> 内,您需要按原样返回孩子:

PrivateRoute