ReactJS - 渲染没有返回任何内容 [英] ReactJS - Nothing was returned from render

查看:50
本文介绍了ReactJS - 渲染没有返回任何内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

渲染没有返回任何内容.这通常意味着缺少 return 语句.或者,不渲染任何内容,返回 null.

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.

我有一个与此消息相关的问题.这是我的组件导致错误:

I Have an issue related to this message. This is my component that causes the error:

import React from 'react';
import Thumbnail from './Thumbnail';

const AlbumList = ({ results }) => {
  let collections = [];
  let albums = { };

Object.values(results).map((item, i) => {
  if(!collections.includes(item.collectionId)) {
    collections.push(item.collectionId);
    albums[i] = {id: item.collectionId, cover: item.artworkUrl100}
  }
return albums;
});

Object.values(albums).forEach(element => {
 return (
  <Thumbnail source={element.cover} />
  )
 })
}

export default AlbumList;

缩略图只是一个基本组件,例如:

Thumbnail is just a basic Component like:

import React from 'react';

const Thumbnail = ({source}) =>  {
  return(
    <div>
      <img src={source} alt="album cover"/>
    </div>
 )
}

export default Thumbnail;

)}导出默认缩略图;

I've been looking for the error like an hour or so. What am I missing?

我找了一个小时左右的错误.我错过了什么?

解决方案

推荐答案

注意 map 返回一个列表,而 forEach 返回 undefined.

You don't return anything from your functional Component Plus forEach does not return anything, instead change it to map.

你没有从你的函数式 Component Plus 返回任何东西 forEach 没有返回任何东西,而是把它改成 map.

Also you need to set the unique key to Thumbnail component in loop

还需要在循环中设置缩略图组件的唯一键

return Object.values(albums).map((element, index) => { return ( <Thumbnail key={"Key-"+index} source={element.cover} /> ) })

I would suggest to read this article map vs. forEach

这篇关于ReactJS - 渲染没有返回任何内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆