meteor 1.3 + react : detect subscription failure?

标签 meteor meteor-publications meteor-react

我有一个简单的 Meteor 订阅,并且在加载数据时显示加载消息。但我不知道如果订阅失败如何显示错误消息。

export const MyAwesomeComponent = createContainer(() => {
  let sub = Meteor.subscribe('some-data');
  if (!sub.ready()) return { message: 'Loading...'};
  if (sub.failed()) return { message: 'Failed.' }; // How to do this?
  return {
    data: Data.find().fetch()
  }
}, MyInternalRenderComponent);

问题是,订阅对象没有 failed()方法,只有一个 ready()询问。如何将订阅失败作为 Prop 传递给 createContainer()方法?

我知道Meteor.subscribe方法有一个 onStop这种情况下的回调,但我不知道如何将它粘合在一起以传递属性。

最佳答案

经过大量研究,我设法让这个工作,我认为它回答了你的问题。

请记住,我使用的是 Meteor 1.6,但它应该为您提供信息以使其在您身边工作。

关于出版/出版:

  try {
    // get the data and add it to the publication
    ...
    self.ready();
  } catch (exception) {
    logger.error(exception);
    // send the exception to the client through the publication
    this.error(new Meteor.Error('500', 'Error getting data from API', exception));
  }

在 UI 组件上:
const errorFromApi = new ReactiveVar();

export default withTracker(({ match }) => {
  const companyId = match.params._id;
  let subscription;

  if (!errorFromApi.get()) {
    subscription = Meteor.subscribe('company.view', companyId, {
      onStop: function (e) {
        errorFromApi.set(e);
      }
    });
  } else {
    subscription = {
      ready: () => {
        return false;
      }
    };
  }

  return {
    loading: !subscription.ready(),
    company: Companies.findOne(companyId),
    error: errorFromApi.get()
  };
})(CompanyView);

从这里您需要做的就是获取错误 Prop 并根据需要渲染组件。

这是error的结构prop(从 onStop 回调接收到 subscribe ):
{
  error: String,
  reason: String,
  details: String
}

[编辑]

原因是在 Meteor.subscribe() 周围有条件是为了避免您从自然中获得的烦人的无限循环 withTracker()更新,这将导致新订阅/发布中的新错误等。

关于 meteor 1.3 + react : detect subscription failure?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36647681/

相关文章:

meteor - 如何访问CreateContainer中的原始props?

meteor - template.$(selector) 不工作 meteor

javascript - AWS SendRawEmail 与 Meteor

javascript - 如何通过 Meteor 中的隐藏字段将 _id 传递给 autoForm?

javascript - meteor :Accounts.createUser() 不创建用户

javascript - ES6 箭头函数正在改变 Meteor.publish 中 this 的范围

javascript - Meteor:为集合服务器端创建过滤器并将它们存储在本地集合中。好主意?

reactjs - 使用 vscode react typescript 导入语法问题

javascript - HammerJS 与 Meteor 和 ReactJS 集成