2017-01-18 196 views
1

我有一個名爲Items的集合,其字段爲namecategory。 在/imports/api/Items.jsSIMPL-架構定義爲:流星React組合集合

const LibItems = new Mongo.Collection('libitems'); 
LibItems.schema = new SimpleSchema({ 
    category: String, 
    text: String, 
}); 
LibItems.attachSchema(LibItems.schema); 
if (Meteor.isServer) { 
    Meteor.publish('allLibItems', function() { 
    return LibItems.find({},); 
    }); 
} 
export default LibItems; 

在頁面上,我想每個組獨特類別的物品;並只顯示所選類別的項目(通過點擊類別)。 所以在imports/client/libview.js底部的項目都是進口的,獨特的類返回:

export default createContainer(() => { 
    Meteor.subscribe('allLibItems'); 
    var libitems = LibItems.find({}, {sort: {category: 1}}).fetch(); 
    return { 
    libitems: libitems, 
    categories: _.uniq(
     libitems, false, 
     function(libitems) {return libitems.category} 
    ), 
    } 
}, LibView); 

render()代碼,renderCategory()被稱爲列出類別:

renderCategories() { 
    return this.props.categories.map((category) => { 
    return (
     <li key={category._id} onClick={this.selectCategory.bind(null, category)}>{category.category}</li> 
    ); 
    }); 
} 

如何獲得項目選擇的類別? 我對ReactJS和流星相對比較陌生;並且可能會有一種更優雅的方式來對每個獨特類別的項目進行分組。

回答

1

鑑於selectedCategory變量用於存儲所選類別,因此您可以通過find來獲取所選類別的項目。

export default createContainer(() => { 
    Meteor.subscribe('allLibItems'); 
    var libitems = LibItems.find({ 
    category: selectedCategory, 
    }).fetch(); 

    return { 
    libitems: libitems, 
    categories: // ..., 
    } 
}, LibView); 

更新

有很多方法可以選擇的類別存儲在selectedCategory,你只需要確保selectedCategory是反應性的。這裏我用ReactiveVar以實現:

const selectedCategory = new ReactiveVar(); 

function setSelectedCategory(newVal) { 
    selectedCategory.set(newVal); 
} 

export default createContainer(() => { 
    Meteor.subscribe('allLibItems'); 
    const libitems = LibItems.find({ 
    category: selectedCategory.get(), 
    }).fetch(); 

    return { 
    // pass setSelectedCategory down to LibView 
    setSelectedCategory: setSelectedCategory, 
    libitems: libitems, 
    categories: // ..., 
    } 
}, LibView); 

內。然後LibView組件:

selectCategory(category) { 
    this.props.setSelectedCategory(category); 
    // ... 
} 
+0

如何通過對'selectedCategory'狀態? – API

+0

@API讓我檢查我的更新回答 – Khang

+0

>未捕獲TypeError:this.setSelectedCategory不是在LibView.selectCategory函數 – API