加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Meteor 1.3 React:检测订阅失败?

发布时间:2020-12-15 20:19:10 所属栏目:百科 来源:网络整理
导读:我有一个简单的Meteor订阅,我在加载数据时显示加载消息.但是,如果订阅失败,我不知道如何显示错误消息. export const MyAwesomeComponent = createContainer(() = { let sub = Meteor.subscribe('some-data'); if (!sub.ready()) return { message: 'Loading.
我有一个简单的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()查询.如何在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);

从这里你需要做的就是得到错误道具并根据需要渲染组件.

这是错误道具的结构(在订阅的onStop回调中收到):

{
  error: String,reason: String,details: String
}

[编辑]

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读