必须返回有效的React元素(或null)

时间:2016-09-01 17:27:37

标签: meteor reactjs

此Meteor React代码产生浏览器控制台错误:

  

警告:ListItems(...):必须返回有效的React元素(或null)。您可能已返回undefined,数组或其他一些无效对象。

Tracker重新计算功能的例外:

知道为什么吗?感谢

//myList.jsx

import React from 'react';

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

export const ListItems = ({listItems}) => {
  <ol>{renderIfData(listItems)}</ol>
};


//cars.jsx

  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 :(得分:1)

除了这部分外,一切看起来都不错:

return listItems.map((item) => {
  return <li key={item._id}>{item.car}</li>;
});

此操作的结果是一个元素数组,并且React会严格阻止它与您收到的错误类型。事实上,在React 16中,他们承诺允许这样做,但你可能会使用15版。无论如何,我建议在任何地方返回一个根元素,所以整个事情看起来像

//myList.jsx

import React from 'react';

export const ListItems = ({listItems}) => {
  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>
    );
  }
};


//cars.jsx

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'));