首页 > 解决方案 > 使用 HOC 反应路由器渲染方法

问题描述

我试图在 react-router-dom (5.0.1)中实现这个逻辑。这是我的路线:

    <Route
      path="/available-days"
      render={props => isAdmin ? Auth(UserProfileView) : <Redirect to='/dashboard'/>}
      />

什么时候idAdmintrue导致错误:Objects are not valid as a React child. 我也试过这个:

    <Route
      path="/available-days"
      render={props => isAdmin ? Auth(UserProfileView)({ ...props }) : <Redirect to='/dashboard'/>}
    />

然后我看到了TypeError: Object(...)(...) is not a function。为什么我不能在渲染方法中使用 HOC,我怎样才能让它工作?顺便说一句Auth(UserProfileView),如果放在组件方法中,效果很好。

标签: reactjsreact-routerreact-router-dom

解决方案


不要在渲染方法中使用 HOC,请参见此处https://reactjs.org/docs/higher-order-components.html

你可以试试

const UserProfileViewWithAuth = Auth(UserProfileView)

<Route
   path="/available-days"
   render={props => isAdmin ? <UserProfileViewWithAuth {...props} /> : <Redirect to='/dashboard'/>}
/>

推荐阅读