ReactJS - 渲染没有返回任何内容 [英] ReactJS - Nothing was returned from render
问题描述
渲染没有返回任何内容.这通常意味着缺少 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屋!