如何使用 react-app-link toRoute({render}) 创建受保护的路由
How to create protected routes with react-app-link toRoute({render})
我正在通过使用 react-app-link 处理路由来将代码重构为 DRY。
我的大部分路线都受到保护,使用 MyLocation.toRoute() 时我无法保护我的路线。
我已经成功生成不受保护的路由。
但是当试图保护路由时,我收到了很多神秘的错误消息。
不幸的是,ract-app-link 文档没有详细介绍渲染选项。
//Link object
const wholeNbr = Yup.number().integer().positive()
const MyLocation = new Location('/doc/:id', {id : wholeNbr.required()})
//Unprotected route - Working code:
{ MyLocation.toRoute({ component: MyComponent, invalid: NotFoundPage }, true) }
//Protected route - Not working:
const privateLocation = (isAuthenticated, Component) => (
isAuthenticated ?
(
<Component />
):(
<Redirect to="/" /> //redirect to login page
)
)
...
<Router history={history}>
...
<Switch>
...
{ CategoryLocation.toRoute({ render: privateLocation(isAuthenticated, MyComponent), invalid: NotFoundPage }, true) }
...
</Switch>
</Router>
我希望组件能够呈现,但收到错误 "TypeError: _render is not a function"
我找到了解决办法!我没有将函数传递给 render 道具。
代码应为:
{ CategoryLocation.toRoute({ render: () => privateLocation(isAuthenticated, MyComponent), invalid: NotFoundPage }, true) }
我正在通过使用 react-app-link 处理路由来将代码重构为 DRY。 我的大部分路线都受到保护,使用 MyLocation.toRoute() 时我无法保护我的路线。
我已经成功生成不受保护的路由。 但是当试图保护路由时,我收到了很多神秘的错误消息。 不幸的是,ract-app-link 文档没有详细介绍渲染选项。
//Link object
const wholeNbr = Yup.number().integer().positive()
const MyLocation = new Location('/doc/:id', {id : wholeNbr.required()})
//Unprotected route - Working code:
{ MyLocation.toRoute({ component: MyComponent, invalid: NotFoundPage }, true) }
//Protected route - Not working:
const privateLocation = (isAuthenticated, Component) => (
isAuthenticated ?
(
<Component />
):(
<Redirect to="/" /> //redirect to login page
)
)
...
<Router history={history}>
...
<Switch>
...
{ CategoryLocation.toRoute({ render: privateLocation(isAuthenticated, MyComponent), invalid: NotFoundPage }, true) }
...
</Switch>
</Router>
我希望组件能够呈现,但收到错误 "TypeError: _render is not a function"
我找到了解决办法!我没有将函数传递给 render 道具。 代码应为:
{ CategoryLocation.toRoute({ render: () => privateLocation(isAuthenticated, MyComponent), invalid: NotFoundPage }, true) }