【问题标题】:Cannot read history from useHistory() in HOC Component无法从 HOC 组件中的 useHistory() 读取历史记录
【发布时间】:2020-07-06 16:20:49
【问题描述】:

为了在我的应用程序中处理身份验证/条件路由,我决定引入一个 HOC 组件,该组件基于 switch 语句检查是否应该呈现组件。

当然,我可以通过在组件本身中定义条件来获得相同的结果,但现在它允许我有一个文件来处理这个问题。

但是,使用 useHistory() 挂钩似乎将 history 作为未定义返回。可能是因为我的应用路由不是以传统方式编写的(AllowAccess 是这里的 HOC 组件):

<Router>
  <Switch>
    <Route exact path='/success' component={AllowAccess(SuccessComponent)}></Route>
    <Route render={() => <Redirect to="/" />} />
  </Switch>
</Router>

有没有办法让我可以从 useHistory 钩子中访问历史道具,并将它们作为“普通”组件在 HOC 中使用?

【问题讨论】:

    标签: react-router react-router-dom react-router-v4


    【解决方案1】:

    当我看到你的代码时,我真的不明白为什么它对你没有帮助,但我在这里使用 PrivateRoute 文件来处理对路由的访问。 但是为什么要从 HOC 访问 useHistory

      const PrivateRoute = ({ component: Component,isAuthenticated, ...rest }) => {
      return (
        <Route {...rest} render={props =>
          !isAuthenticated ? (
            <Redirect to='/'/>
          ) : (
            <Component {...props} />
          )
        }
        />
      );
    };
    

    实现

    `<PrivateRoute exa`ct path="/add" component={AddEmployee} isAuthenticated={isAdmin}/>
    

    【讨论】:

      猜你喜欢
      • 2021-09-03
      • 1970-01-01
      • 2020-02-25
      • 2020-11-24
      • 2020-02-01
      • 2020-03-27
      • 1970-01-01
      • 2019-05-14
      • 1970-01-01
      相关资源
      最近更新 更多