简体   繁体   English

Mobx的React-Router中间件

[英]React-Router Middleware with Mobx

I am trying to set up an Admin page that is only accessible to people with a user "level" greater than 2. I am using MobX and React-Router. 我试图设置一个“管理员”页面,该页面只能由用户“级别”大于2的人员访问。我正在使用MobX和React-Router。 The problem is likely based on the fact that I don't know how to connect to the MobX store properly. 该问题可能是由于我不知道如何正确连接到MobX存储而引起的。 I am importing a function, isAdmin , that is located in a seperate file from routes.js . 我正在导入一个名为isAdmin的函数,该函数位于route.js的单独文件中。 The function looks like: 该函数如下所示:

export const isAdmin = (nextState, replace) => {
    const user = this.context.store.auth.user;
    if (user.level < 2 || !user) {
        replace({
            pathname: '/',
        });
    }
};

This is loosely based on the final example from the gitHub page for react-router located here . 这大致基于gitHub页面上最后一个示例,该示例位于此处的 react-router

Thanks for any help! 谢谢你的帮助!

This link explains what Context object is and where to use it. 链接说明什么是Context对象以及在哪里使用它。 `isAdmin' function will need access to your Store class to get the user level. isAdmin函数将需要访问您的Store类以获取用户级别。

Create an AuthStore (/stores/auth.js) - 创建一个AuthStore(/stores/auth.js)-

import { observable, computed } from 'mobx';
import singleton from 'singleton';

export default class Auth extends singleton {
  @observable user = null;

  @computed get isLoggedIn() {
    return !!this.user;
  }

  login(username, password) {
    return post('/api/auth/login', {
      username, password
    })
    .then((res) => {
      this.user = res.data.user;
      return res;
    });
  }

  logout() {
    Storage.remove('token');
    return get('/api/auth/logout');
  }
}

In your routes file, you can import the AuthStore and use it like this 在您的路线文件中,您可以导入AuthStore并像这样使用它

import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Auth from './stores/Auth'; // note: we can use the same store here..

function authRequired(nextState, replace) {
  if (!Auth.isLoggedIn) {
    replace('/login');
  }
}

export default (
  <Route name="root" path="/" component={App}>
    <Route name="login" path="login" component={Login} />
    <Route name="admin" path="admin" onEnter={authRequired} component={Admin}>
      <IndexRoute name="dashboard" component={Dashboard} />
    </Route>
  </Route>
);

This stackoverflow question should give you more info 这个stackoverflow问题应该给您更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM