[英]how to get data from react-meteor-data container only when it's ready?
由于isReady保持为false,因此无法从容器中获取数据。 当在MeteorToys中查看时,该集合确实已加载,因此我不明白为什么。
在服务器上,我定义了StaticContents集合,该集合将加载“ api”数据。 (我现在自己输入)
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,内容为空数组。 我应该如何解决这个问题,为什么加载时间这么长?
我正在使用官方的流星指南“休息时加载”作为指南。 https://guide.meteor.com/data-loading.html#loading-from-rest
由于您是在componentWillMount中记录this.props
的,因此它将被执行一次-在<Dashboard>挂载之前,也可能在轮询-发布订阅准备就绪之前。 在此期间, isReady和内容将是您所获得的。 随后,订阅应准备就绪,道具将成为您所期望的。
您可以将console.log
放入渲染器中,以检查每个渲染器上的道具值。
同样在
{this.props.isReady && this.props.content.name}
this.props.content是一个数组,因此引用名称字段没有多大意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.