【问题标题】:How to pass history to the Nav component inside the BrowserRouter in App.js如何将历史记录传递给 App.js 中 BrowserRouter 内的 Nav 组件
【发布时间】:2021-09-02 06:58:38
【问题描述】:

我在 App.js 文件中有以下代码:

<BrowserRouter>
    <Nav />
    <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/barium" component={Barium} />
        <Route path="/gamma" component={Gamma} />
        <Route path="/h2spp" component={H2S} />
        <Route path="/texas" component={TexasGasEst} />
        <PrivateRoute path="/exam" component={Exam} />
        <PrivateRoute path="/profile" component={Profile} />
        <PrivateRoute path="/students" component={Students} />
        <Route path="/*" component={Home} />
    </Switch>
    <Footer />
</BrowserRouter>

在导航组件中,我有一个登录模式。 我想通过 Nav 组件将历史道具传递给登录模式,以便在登录后立即创建 history.push

【问题讨论】:

    标签: reactjs router history


    【解决方案1】:

    因为&lt;Nav&gt;&lt;BrowserRouter&gt; 的后代,您可以使用其中的useHistory 挂钩来访问History 实例:

    import { useHistory } from "react-router-dom";
    
    function Nav() {
      const history = useHistory();
    
      function onAfterLogin() {
        history.push("/welcome");
      }
    
      // ...
    }
    

    【讨论】:

    • 感谢您的帮助。
    猜你喜欢
    • 2022-10-15
    • 2018-12-31
    • 1970-01-01
    • 2020-05-24
    • 1970-01-01
    • 2018-04-08
    • 1970-01-01
    • 2020-05-18
    • 2019-12-26
    相关资源
    最近更新 更多