我正在使用 Meteor 和 React。我有一个包含在 react-composer 中的组件来订阅我的数据。我将服务器发布的限制设置为 10,并在每次用户将按钮滚动到另一个 10 时提高此限制。
问题是,整个组件似乎都在刷新,而不是仅将 10 个新元素添加到视图中。我如何才能重新加载仅附加数据,而不进行总“页面”刷新?
原则上,我使用 javascript 来检测用户何时到达页面底部,然后在父组件中触发一个函数来更改我的 LocationList 的限制状态,然后触发服务器发布以加载更多位置。
服务器/Publication.js
Meteor.publish("Locations", function(settings) {
check(settings, Object);
ReactiveAggregate(this, Locations, [
{ $limit: settings.limit },
{ $project: {
name: '$name',
}},
]);
});
客户端/LocationList.jsx
class LocationList extends React.Component {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
}
handleScroll() {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight - 100) {
// bottom reached
this.props.onLoadMore();
} else {
// not bottom
}
}
componentDidMount() {
window.addEventListener("scroll", this.handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this.handleScroll);
}
render() {
... something
}
}
function composer(props, onData) {
const settings = {
limit: props.limit,
};
const locationSubscription = Meteor.subscribe('Locations', settings);
if(locationSubscription.ready()) {
locations = Locations.find({}, {limit: props.limit}).fetch();
const data = {
ready: true,
locations: locations,
}
onData(null, data);
} else {
onData(null, {ready: false});
}
}
const options = {
loadingHandler: () => (<p>Loading... </p>)
};
export default composeWithTracker(composer, options)(LocationList);
客户端/LocationListLoader.jsx
export default class LocationListLoader extends React.Component {
constructor(props) {
super(props);
this.state = {
limit: 9
};
this.loadMore = this.loadMore.bind(this);
}
componentWillReceiveProps(nextProps) {
if(this.props.category != nextProps.category) {
this.setState({ limit: 9 });
}
}
loadMore() {
const newLimit = this.state.limit + 6;
this.setState({ limit: newLimit });
}
render() {
return (
<LocationList onLoadMore={this.loadMore} limit={this.state.limit} />
)
}
}