必须返回有效的 React 元素(或 null) [英] A valid React element (or null) must be returned
问题描述
这个 Meteor React 代码产生了浏览器控制台错误:
This Meteor React code is producing browser console error:
警告:ListItems(...):必须返回有效的 React 元素(或 null).您可能返回了 undefined、数组或其他一些无效对象.
Warning: ListItems(...): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.
Tracker 重新计算函数的异常:
Exception from Tracker recompute function:
知道为什么吗?谢谢
//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'));
推荐答案
除了这部分外,一切都很好:
Everything looks nice except this part:
return listItems.map((item) => {
return <li key={item._id}>{item.car}</li>;
});
这个操作的结果是一个元素数组,React 会以你收到的那种错误来阻止它.事实上,在 React 16 中,他们承诺允许这样做,但您可能使用版本 15.无论如何,我建议在任何地方都返回一个根元素,所以整个事情看起来像
The result of this operation is an array of elements, and React discourages it with exactly the kind of error you're receiving. In fact, in React 16, they promise to allow this, but you're likely using version 15. Anyway, I'd recommend returning a single root element everywhere, so the whole thing would look like
//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'));
这篇关于必须返回有效的 React 元素(或 null)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!