[英]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.