首页 > 解决方案 > 订阅中的 Meteor + React 过滤器

问题描述

我正在使用流星并与 withTracker 做出反应以获取动态数据。我有大量数据,我必须在服务器端过滤数据,否则客户端崩溃。为此,我使用过滤器作为出版物的参数。

问题是当我更改已经在过去请求中的查询的一个字段时,组件不会更新。为了解决这个问题,我添加或删除了一个 {"_id":{$exists:true}} 以使组件刷新而不使用缓存数据。

服务器端发布:

Meteor.publish('subredOrders', function(filters={}, sort={"_id":1}, pagination={skip:0,limit:2000}, fields={}) {
    return SubredOrders.find(filters, {sort: sort, skip: pagination.skip, limit: pagination.limit, fields: fields});
});

Meteor.publish('subredOrders.count', function(filters={}) {
    Counts.publish(this, 'subredOrders.count', SubredOrders.find(filters), {fastCount: true});
});

客户端组件:

class MyTable extends Component {

    constructor(props) {
        super(props);

        this.state = {
            filtersPanel: false,
        };
        this.temp = {filters: this.props.params.filters};
    }

    toggleFiltersPanel(){
        let filtersPanel = this.state.filtersPanel;
        filtersPanel = !filtersPanel;
        *if (!filtersPanel) {
            if (this.temp.filters["$and"] && this.temp.filters["$and"].length > 0) {
                let removed = false;
                for(let i=0; i < this.temp.filters["$and"].length; i++){
                    for(let key in this.temp.filters["$and"][i]) {
                        if (key === "_id") {
                            this.temp.filters["$and"].splice(i, 1);
                            removed = true;
                        }
                    }
                }
                if (!removed) this.temp.filters["$and"].push({"_id":{$exists:true}});
            }
            this.props.updateParams("filters", this.temp.filters);
        }*
        this.setState({filtersPanel: filtersPanel});
    }

    ...

    render() {
        ...
    }
}

export default withTracker((props) => {
    if (props.collector == null) return {};
    let sub = Meteor.subscribe(props.subscription, props.params.filters, props.params.sort, props.params.pagination);
    let countSub = Meteor.subscribe(props.subscription+".count", props.params.filters);

    return {
        collection: props.collector.find({}, {limit: props.params.pagination.limit}).fetch(),
        dataLoaded: sub.ready() && countSub.ready(),
    }
})(MyTable);

我的解决方案是在 2 *. 当用户关闭 filtersPanel 时,它会启动 toggleFiltersPanel 并检查请求的过滤器部分是否具有 _id,然后推送或删除以使其与过去的不同。如果用户更改一个字段 2 次,则请求仅在第一次有效。这就是为什么我必须这样做,但我不明白为什么......

这不是一个优化的解决方案,也许有人有其他想法,或者至少可以解释我为什么必须这样做才能使其工作?

谢谢 !

标签: javascriptreactjsmeteor

解决方案


推荐阅读