【问题标题】:ReactJS: How can I programmatically redirect a user to another page?ReactJS:如何以编程方式将用户重定向到另一个页面?
【发布时间】:2019-12-04 07:27:05
【问题描述】:

我有一个基本的 ReactJS 4.0.1 应用程序,使用 react-router-dom 5.0.1 设置路由。

我还有一个中间件,用于检查用户的会话时间是否已过期。从那里,我想简单地将用户重定向到登录页面。

我真的只是想换页。如果这是在 .net 中,我会打电话:

return RedirectToAction("Index", model);

很简单。

以前,为了更改不同组件中的内容,我在渲染部分中有一个 if 语句,它将通过返回来重定向:

<Redirect to={{ pathname: '/signin' }}/>

给用户。如果用户采取了触发组件内代码的操作,但我正在处理的逻辑在中间件中,则此方法有效。

我试过了 history.push、goto、location.push、store.push 等... 我无法让这些工作。 通过我的中间件,我可以从 redux 访问 Store。我能用它做什么?

【问题讨论】:

    标签: reactjs redux react-router-dom


    【解决方案1】:

    您可以使用history 对象。只需导出history 对象并调用history.push('some-page')。我在这里做了一个演示https://codesandbox.io/s/serverless-fire-1vihp

    export const history = createBrowserHistory()

    并将历史道具传递给路由器

    <Router history={history}>

    在中间件文件中只需调用history.push('some-page')

    另一种方法是使用像react-router-redux这样的库,

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-31
      • 1970-01-01
      • 2012-04-05
      • 1970-01-01
      • 2022-01-04
      • 2023-03-29
      • 1970-01-01
      相关资源
      最近更新 更多