【发布时间】:2017-09-22 23:41:55
【问题描述】:
我有一个带有一些设置的 Meteor 订阅,因此我不会发布我的整个集合服务器端。订阅将从meteor/react-meteor-data 中的createContainer() 中获取并显示在一个简单的<ul> 列表中,其中我还将document.id 作为键添加到<li> 元素中。
不幸的是,一旦我增加了订阅第二个订阅参数 (Meteor.subscripte('Collections', settings.limit) 中的 settings.limit,整个 <ul> 列表就会重新呈现?我可以做些什么来增加发布限制,同时只添加新的列表元素?
附:当我通过 Collection.find({}, {limit: newLimit}).fetch() 发布全部 Collection 并更改客户端中的限制时,react 正在按预期工作:保留旧元素并添加新元素!
客户端
import React, { Component } from 'react';
import { Locations } from '/both/collections/locations.js';
import { Events } from '/both/collections/events.js';
import { createContainer } from 'meteor/react-meteor-data';
class Content extends React.Component {
constructor(props) {
super(props);
this.renderLocations = this.renderLocations.bind(this);
}
renderLocations() {
return this.props.locations.map(function(location) {
return (<li key={location._id} >{location.name}</li>);
});
}
render() {
console.log(this.props);
return !this.props.loading && (
<div>
<ul>
{this.renderLocations()}
</ul>
<h1 onClick={this.props.increaseLimit}> Limit </h1>
<div style={{marginBottom: "100px"}}></div>
</div>
);
}
}
export default createContainer((props) => {
const settings = {
limit: props.limit,
}
const locationsSubscribe = Meteor.subscribe('Locations', settings);
const loading = !locationsSubscribe.ready();
if(loading) {
return { loading };
} else {
const _locations = Locations.find({}, {fields: { name: 1}, sort: { name: 1 }}).fetch();
return {
loading,
locations: _locations,
increaseLimit: props.increaseLimit,
};
}
}, Content);
服务器端
Meteor.publish('Locations', function(settings) {
return Locations.find({}, {limit: settings.limit, sort: { name: 1} } );
});
Collection.find().fetch() 响应
[
{
"name": "3-Master Bike-Style",
"_id": "N9rWyZMdxEe6jhNW2"
},
{
"name": "43einhalb",
"_id": "bPgpBm59LohGLaAsf"
},
{
"name": "A&B Döner",
"_id": "qTNMk73ThvaPxGWqM"
},
{
"name": "A.T.U ",
"_id": "aWzSmp2zZ8etDhHk6"
},
{
"name": "AIKO Sushibar - Hot Wok",
"_id": "9pQJgeBNo5gFRkKdF"
},
{
"name": "AXA Stefan Hahn",
"_id": "d9f6mTrSTGCoeKPbP"
}
]
【问题讨论】:
-
您能否分享您在 2 订阅中收集数据的 console.log。可能存在一些逻辑错误。请确保您没有将新数据推送到旧数组。
-
@PankajJatav 你的意思是获取的数组?由 Collection.find().fetch() 返回?
-
是的,请分享。
-
@PankajJatav 我添加了代码并尝试复制
_location变量 -
能否也分享一下服务器代码。您的客户端代码看起来不错。
标签: reactjs meteor publish-subscribe