7

我正在尝试在我的 Meteor 应用程序中使用 react-router 实现 alanning Meteor-roles。一切正常,除了我无法正确管理使用alanning角色限制路线或Meteor.user()

我尝试使用流星角色:

我正在尝试onEnter={requireVerified}在我的路线上使用。这是代码:

const requireVerified = (nextState, replace) => {
    if (!Roles.userIsInRole(Meteor.userId(), ['verified'],'user_default')) {
        replace({
            pathname: '/account/verify',
            state: { nextPathname: nextState.location.pathname },
        });
    }
};

我尝试使用 Meteor.user():

const requireVerified = (nextState, replace) => {
  if (!Meteor.user().isverified == true) {
    replace({
      pathname: '/account/verify',
      state: { nextPathname: nextState.location.pathname },
    });
  }
};

因此,当我单击路线链接时,这是有效的,但是当我手动刷新(F5)时,它不起作用。深入研究后,我发现Meteor.user()手动刷新页面时还没有准备好。

我知道 Meteor.userid() 或 Meteor.logginIn() 正在工作,但我不仅想验证它们是否被记录,而且它们是否被“验证”或具有作用。

我还尝试使用 react、withcomponentDidMount()或来检查组件内部componentWillMount(),在这两种情况下都是相同的,在安装组件之前手动刷新不会加载Meteor.user()

那么用meteor/aling角色+反应路由器限制组件/路由的最佳方法是什么?(我在 TheMeteorChef 的基地内使用 react-komposer)

谢谢你。

4

1 回答 1

1

注意我还没有尝试过,这只是一个建议

您可以尝试的一件事是componentWillReceiveProps与'react-meteor-data'中的createContainer一起使用,如下所示:

import React, { Component, PropTypes } from 'react';
import { Meteor } from 'meteor/meteor';
import { createContainer } from 'meteor/react-meteor-data';
import { Roles } from 'meteor/alanning:roles';

class MyComponent extends Component {
  componentWillReceiveProps(nextProps) {
    const { user } = nextProps;
    if (user && !Roles.userIsInRole(user._id, ['verified'], 'user_default')) {
      browserHistory.push('/account/verify');
    }
    // If Meteor.user() is not ready, this will be skipped.
  }
}

MyComponent.propTypes = {
  user: PropTypes.object,
};

export default createContainer(() => {
  const user = Meteor.user() || null;
  return { user };
}, MyComponent);

为了解释流程,当页面加载时,如您所说 Meteor.user() 未定义,因此您无法检查权限。但是,当 Meteor.user() 被定义时,这将触发模板的刷新,并且新的 props 将被传递给componentWillReceiveProps. 此时您可以检查是否user已定义并在需要时重定向。

为了确保不会遗漏任何内容,我实际上也会将验证放入其中constructor()(定义一个将道具作为参数并在两者中调用它的函数constructor()and componentWillReceiveProps())。

于 2016-10-07T09:00:46.887 回答