javascript - ReactJS 重定向

标签 javascript redirect reactjs react-router

我在我的应用程序中使用了 ReactJSreact-router。我需要做下一件事:当用户打开页面时 - 检查他是否登录,如果是,则重定向到 /auth 页面。我在做下一件事:

componentWillMount: function() {
    if (sessionStorage["auth"] == null) {
        this.transitionTo("/auth");
    }
},

在浏览器 url 中,它确实会重定向到 /auth,呈现 /auth 页面,然后用当前组件覆盖它。所以这里的问题是:如何取消当前组件的渲染,或者如何以其他方式进行重定向?谢谢。

最佳答案

看看 react-router 示例 auth-with-shared-root: https://github.com/rackt/react-router/tree/master/examples/auth-with-shared-root

他们基本上做的是检查路线的入口。查看文件 config/routes.js 第 36、51 和 89 行:

{ onEnter: redirectToLogin,
      childRoutes: [
        // Protected nested routes for the dashboard
        { path: '/page2',
          getComponent: (location, cb) => {
            require.ensure([], (require) => {
              cb(null, require('../components/PageTwo'))
            })
          }
        }
        // other protected routes...
     ]
}

当路由 /page2 被输入或推送到时,该路由将调用函数 redirectToLogin。该函数可以检查用户是否通过 auth.loggedIn()

进行了身份验证
function redirectToLogin(nextState, replace) {
  if (!auth.loggedIn()) {
    replace({
      pathname: '/login',
      state: { nextPathname: nextState.location.pathname }
    })
  }
}

如果用户未登录,该函数将替换到 /login 的路由,用户可以在此处验证自己。

关于javascript - ReactJS 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28040912/

相关文章:

javascript - 在 django 模板的内部 css 中使用上下文变量

wordpress - anchor 标记中的onclick和href重定向

reactjs - 将 React 生成的 pdf 上传到谷歌驱动器

javascript - 在动态创建的 HTML 表中编写 Javascript If 条件

javascript - 如何使用 Javascript for 循环创建重复的 HTML?

django - 重定向 Django View

javascript - Reactjs:如何在安装组件之前获取要加载的数据?

javascript - 类型错误 : cannot read property of undefined (reading 'map' ) while fetching from API

javascript - After Effects 应用预设 : bad path

redirect - Electron:阻止/取消页面导航