Meteor导出集合到React组件

时间:2016-09-01 22:12:05

标签: meteor reactjs

此Meteor代码无法在浏览器中显示mongo集合CarsCol中的数据 我究竟做错了什么?感谢

// /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

1 个答案:

答案 0 :(得分:0)

非常熟悉的问题。尝试将引用传递给集合而不是通过props将获取的数据传递给组件,如下所示:

// /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%的代码。但希望这个想法很明确:当订阅准备就绪时,您通过道具传递集合本身,而不是从中获取的数据,然后在组件本身内执行获取。这样,您还可以保持反应性,例如更新集合时,组件将被更新(呈现)。