我想利用react router的onEnter处理程序来提示用户在进入受限路由时进行身份验证.

到目前为止,我的routes.js文件看起来像这样:

import React from 'react';
import { Route, IndexRoute } from 'react-router';

export default (
    <Route   path="/"         component={App}>
      <IndexRoute             component={Landing} />
      <Route path="learn"     component={Learn} />
      <Route path="about"     component={About} />
      <Route path="downloads" component={Downloads} onEnter={requireAuth} />
    </Route>
)

理想情况下,我希望我的requireAuth函数是一个redux操作,可以访问存储和当前状态,其工作原理如下:store.dispatch(requireAuth()).

不幸的是,我无法访问此文件中的存储.我不认为我能在这种情况下使用connect来访问我想要的相关操作.我也不能从创建store 的文件中删除import store,因为这在应用程序首次加载时是未定义的.

推荐答案

实现这一点的最简单方法是将存储传递给返回路由的函数(而不是直接返回路由).通过这种方式,您可以通过onEnter和其他方法访问store .

所以对于你的路由:

import React from 'react';
import { Route, IndexRoute } from 'react-router';

export const getRoutes = (store) => (
  const authRequired = (nextState, replaceState) => {
    // Now you can access the store object here.
    const state = store.getState();

    if (!state.user.isAuthenticated) {
      // Not authenticated, redirect to login.
      replaceState({ nextPathname: nextState.location.pathname }, '/login');
    }
  };

  return (
    <Route   path="/"         component={App}>
      <IndexRoute             component={Landing} />
      <Route path="learn"     component={Learn} />
      <Route path="about"     component={About} />
      <Route path="downloads" component={Downloads} onEnter={authRequired} />
    </Route>
  );
)

然后更新主组件以调用getRoutes函数,传入存储:

<Provider store={ store }>
  <Router history={ history }>
    { getRoutes(store) }
  </Router>
</Provider>

至于从requireAuth发送一个动作,你可以这样写你的函数:

const authRequired = (nextState, replaceState, callback) => {
  store.dispatch(requireAuth())  // Assume this action returns a promise
    .then(() => {
      const state = store.getState();

      if (!state.user.isAuthenticated) {
        // Not authenticated, redirect to login.
        replaceState({ nextPathname: nextState.location.pathname }, '/login');
      }

      // All ok
      callback();
    });
};

希望这有帮助.

Reactjs相关问答推荐

条件索引路由

在react.js的条形图中获取错误&unfined是不可迭代的

Formik验证不适用于物料UI自动完成

REACTJS:在Reaction中根据路由路径更改加载器API URL

捕获表单数据时的Reactjs问题

左边框不在图表中显示

在Reaction中管理多个状态

如何在REACTIVE js中动态添加或删除输入字段?

强制 useEffect 仅运行一次

在 React JS 中编辑表格数据

无法在 reactJS 中使用空包装器 <>

如果传递给挂钩的数据需要事先修改,如何使用自定义挂钩?

Select 建议后如何关闭 vscode 添加自动完成={}

如何使图标适合 react-bootstrap 中的行元素

为什么我在此代码段中看不到 useEffect for count = 1?

模块解析失败:意外令牌 (257:106) 您可能需要适当的加载程序来处理此文件类型

组件焦点上的 MUI 更改栏 colored颜色

如何在 v6.4 中将 Auth0 提供程序与新的 createBrowsereRouter 一起使用?

react 路由路由加载器不适用于嵌套组件

如何将本地视频文件上传到 Google Cloud