如何从react-meteor-data容器中获取数据?

时间:2017-07-31 20:44:09

标签: javascript reactjs meteor

我无法从容器中获取数据,因为isReady保持为false。在MeteorToys中查看时,该集合确实已加载,因此我不明白为什么。

在服务器上,我定义了使用“api”数据加载的StaticContents集合。 (我现在输入的是自己)

export const StaticContents = new Mongo.Collection("staticContents");

if (Meteor.isServer) {
  Meteor.publish("polled-publication", function() {
    const publishedKeys = {};
    const poll = () => {
      // Let's assume the data comes back as an array of JSON documents, with an _id field, for simplicity
      const data = [{ _id: 1, name: "jef" }, { _id: 2, name: "jan" }];
      const COLLECTION_NAME = "staticContents";
      data.forEach(doc => {
        if (publishedKeys[doc._id]) {
          this.changed(COLLECTION_NAME, doc._id, doc);
        } else {
          publishedKeys[doc._id] = true;
          this.added(COLLECTION_NAME, doc._id, doc);
        }
      });
    };
    poll();
    this.ready();
  });
}

在客户端上,我导入了这个StaticContents集合和react-meteor-data,并将它放在一个容器中,该容器将这些变量传递给我的react组件。

import { Meteor } from "meteor/meteor";
import { Mongo } from "meteor/mongo";
import { StaticContents } from "../api/gap.js";
import { createContainer } from "meteor/react-meteor-data";
import React, { Component } from "react";

class Dashboard extends Component {
  componentWillMount() {
    console.log("log the props");
    console.log(this.props);
  }
  render() {
    //const gapData = Session.get("gapData");
    return (
      <div className="container">
        <div className="starter-template">
          <h1>This is the dashboard page.</h1>
          <p className="lead">
            Use this document as a way to quickly start any new project.<br />{" "}
            All you get is this text and a mostly barebones HTML document.
          </p>
          <p>
            {this.props.testprop}
            <br />
            {this.props.isReady && this.props.content.name}
            <br />
          </p>
        </div>
      </div>
    );
  }
}

export default createContainer(props => {
  // Do all your reactive data access in this method.
  // Note that this subscription will get cleaned up when your component is unmounted
  const handle = Meteor.subscribe("polled-publication");

  return {
    isReady: handle.ready(),
    content: StaticContents.find({}).fetch(),
    testprop: "this is a testprop"
  };
}, Dashboard);

记录道具时,isReady为false,content为空数组。 我该如何解决这个问题,为什么要加载这么长时间?

我正在使用官方流星指南“从休息中加载”作为指南。 https://guide.meteor.com/data-loading.html#loading-from-rest

1 个答案:

答案 0 :(得分:1)

由于您要在 componentWillMount 中记录this.props,因此会在&lt; Dashboard&gt; 安装之前以及可能在轮询之前执行一次-publication 订阅准备就绪。在此期间, isReady 内容将是您获得的。随后,订阅应该准备就绪,道具将成为您的期望。

您可以将console.log置于渲染中,以检查每个渲染上道具的值。

同样在

{this.props.isReady && this.props.content.name}

this.props.content 是一个数组,因此引用名称字段没有多大意义。