【问题标题】:You may have returned undefined, an array or some other invalid object您可能返回了未定义、数组或其他一些无效对象
【发布时间】:2018-04-23 07:14:41
【问题描述】:
const renderCategories = (props) => {
  console.log(props);
  return props.categories.map(category => (
    <Category
      key={category.categoryID}
      category={category}
      isSelected={props.selectedCategory === category.categoryID}
      setSelectedCategory={props.setSelectedCategory}
    />
  ));
};

这是返回迭代类别的函数。我认为我在语法上犯了一些错误,这就是为什么我收到以下错误,You may have returned undefined, an array or some other invalid object. 我知道这是一个常见问题,但我找不到与我的代码相关的解决方案。

【问题讨论】:

  • 你使用的是什么版本的 React?
  • @riwu - 我使用的是 15.4.0
  • 如何在render() 函数中使用renderCategories()?你能添加代码吗?

标签: javascript reactjs


【解决方案1】:

React v16.0 支持在渲染函数中返回数组。

您需要将其包裹在 div 或其他东西上:

return (
  <div>
    {props.categories.map((category) => (
      <Category
        key={category.categoryID}
        category={category}
        isSelected={props.selectedCategory === category.categoryID}
        setSelectedCategory={props.setSelectedCategory}
      />
    ))}
  </div>
);

【讨论】:

  • @YashSharma 不要忘记,如果您的项目允许,您也可以升级到 React 16。然后你就可以返回数组了。
猜你喜欢
  • 2018-07-02
  • 2016-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多