【问题标题】:React, Nothing was returned from render反应,渲染没有返回任何内容
【发布时间】:2020-06-25 23:57:30
【问题描述】:

我有这个Home 组件:

import Items from './Items';
class Home extends Component{
  render(){
    const { items } = this.props;

    return(
      <div className="container">
          <Items items={items}/>
      </div>
    )
  }
}

而Items就是这个:

import React from 'react';
const Items = (props) => {
    const { items } = props;
    items.map(item=>{
      return(
        <div>
            <p>{item.value}</p>
        </div>
      )
    });
};

export default Items;

我收到此错误:

× 错误:Items(...):渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null。

为什么?如果我需要映射那些 items 数组,我该如何返回。

【问题讨论】:

  • 你需要return.map方法返回的数组。目前,Items 组件不返回任何内容(只有地图回调)
  • return items.map(item=&gt;{?哇,这行得通,是的,我的错误,谢谢

标签: reactjs


【解决方案1】:

当您确实在 map()(或任何使用回调的函数)内返回时,您需要为 React 组件添加额外的返回:

const Items = (props) => {

    const { items } = props;

    return items.map(item=>{
    ^^^^^^
      return(
        <div>
            <p>{item.value}</p>
        </div>
      )
    });
};

您可以通过使用正则括号来简化map() 内的内部回调:

return items.map(item=> (
  <div>
     <p>{item.value}</p>
  </div>
));

这称为隐式返回,当箭头函数内没有块范围{ ... } 时有效。所以:

// These are all equivalent: return value is: [2,4]

[1,2].map(n => n * 2);
[1,2].map(n => (n * 2));
[1,2].map(n => { return (n * 2) });

// This, howover, will return [ undefined, undefined ] because
// there is no return inside the block-scope of the arrow function:

[1,2].map(n => { n * 2 });

与任何类型的箭头函数相同(例如您定义&lt;Items&gt; 组件的方式:

// This will work:

const Items = () => (
  items.map(item => ...)
);

// This will return undefined, and React won't like it:

const Items = () => {
  items.map(item => ...)
}

希望解释是有道理的,如果有不清楚的地方,请添加任何评论!

最后,如果您不希望从 render() 或函数式组件返回任何内容,返回 null 就足够了:

  if (!props.items) {
    return null; // <-- this works
  }

  ...
}

【讨论】:

  • 谢谢伙计,我将使用 => () 代替两个返回。
  • 很高兴能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-05
  • 2021-01-01
  • 2019-04-14
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 2018-07-09
相关资源
最近更新 更多