2016-09-01 53 views
0

這個流星代碼無法在瀏覽器中顯示來自mongo集合CarsCol的數據。
我在做什麼錯?由於流星導出集合到React組件

// /imports/api/collections.js 
export const CarsCol = new Mongo.Collection('carsCol'); 


// /imports/ui/myList.jsx 
import React from 'react'; 

export const ListItems = ({listItems}) => { //<---- {listItems} undefined 
    if (listItems && listItems.length > 0) { 
    return (
     <ol> 
     {listItems.map((item) => (
      <li key={item._id}>{item.car}</li> 
     ))} 
     </ol> 
    ); 
    } else { 
    return (
     <p>No cars yet!</p> //<------------ shows in browser 
    ); 
    } 
}; 


// /client/cars.js 
import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { composeWithTracker } from 'react-komposer'; 
import { ListItems } from '../imports/ui/myList.jsx'; 
import { CarsCol } from '../imports/api/collections.js'; 

const composer = (props, onData) => { 
    const sub = Meteor.subscribe('carsCol'); 
    if (sub.ready()) { 
    const cars = CarsCol.find().fetch(); 
    onData(null, {cars}); 
    } 
}; 

const Container = composeWithTracker(composer) (ListItems); 
ReactDOM.render(<Container />, document.getElementById('react-root')); 

enter image description here

回答

0

非常熟悉的問題。嘗試通過道具通過參考集合,而不是獲取數據的組件,如:

// /imports/api/collections.js 
export const CarsCol = new Mongo.Collection('carsCol'); 


// /imports/ui/myList.jsx 
import React from 'react'; 

export const ListItems = ({cars}) => { 
    const listItems = cars.find().fetch(); // <- fetching data from a collection received as a prop right here 

    if (listItems && listItems.length > 0) { 
    return (
     <ol> 
     {listItems.map((item) => (
      <li key={item._id}>{item.car}</li> 
     ))} 
     </ol> 
    ); 
    } else { 
    return (
     <p>No cars yet!</p> //<------------ shows in browser 
    ); 
    } 
}; 


// /client/cars.js 
import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { composeWithTracker } from 'react-komposer'; 
import { ListItems } from '../imports/ui/myList.jsx'; 
import { CarsCol } from '../imports/api/collections.js'; 

const composer = (props, onData) => { 
    const sub = Meteor.subscribe('carsCol'); 
    if (sub.ready()) { 
    onData(null, { 
     cars: CarsCol // <- now the "cars" prop is the collection 
    }); 
    } 
}; 

const Container = composeWithTracker(composer) (ListItems); 
ReactDOM.render(<Container />, document.getElementById('react-root')); 

我認爲應該工作,雖然我有你沒有共享代碼的100%強烈的感覺參與其中。但希望這個想法是明確的:當訂閱準備就緒時,你通過收集本身,而不是從它獲取的數據,通過道具,然後在組件本身執行提取。這樣,你也可以保留反應性,例如當更新集合時,組件將被更新(呈現)。

+0

我刪除了集合中的所有記錄,但瀏覽器沒有更新顯示任何內容。爲什麼在這種情況下反應性不起作用? –

+0

這是一個很好的問題,我從來沒有見過它不是以你描述的方式工作。我認爲使用[tracker-component](https://github.com/studiointeract/tracker-component)可以解決這個問題,儘管它需要對代碼進行重大更改。 –

+0

我知道在容器內部完成react-kompose反應,因此在函數'compose'內部,它如何響應對mongo集合的更改,將集合提取移到UI組件,而不是像您在接受的答案中所建議的那樣? [https://voice.kadira.io/using-meteor-data-and-react-with-meteor-1-3-13cb0935dedb#.bz29237uj] –