首页 > 解决方案 > “必须返回一个有效的 React 元素(或 null)。” 与 array.map

问题描述

我有下面定义的功能性反应组件:

import React from 'react';
import Cell from './FeedCell';
import PropTypes from 'prop-types';

const Feed = (props) => {
        return props.arr.map((type, index) => {
            return (<Cell />)
        })
};

我收到错误消息:

Feed(...):必须返回一个有效的 React 元素(或 null)。您可能返回了未定义、数组或其他一些无效对象。

我觉得这应该是显而易见的,但我已经尝试了在线提供的解决方案,但我遗漏了一些东西。

标签: javascriptreactjs

解决方案


您当前正在返回一个数组,但您必须返回一个正确的 React 元素。

React.Fragment如果您不想在 DOM 中包含包装元素,则可以将数组包装在 a中。

const Feed = (props) => {
  return (
    <React.Fragment>
      {props.arr.map((type, index) => <Cell />)}
    </React.Fragment>
  );
};

推荐阅读