这里我将播放列表的值发送到控制台,但无法将其显示到UI。
function Sidebar() {
const [{ playlists }, dispatch] = useStateProviderValue();
console.log(playlists);
playlists?.items?.forEach(element => {
console.log(element.name);
});
return (
<div className="sidebar">
<img
className="sidebar__logo"
src="https://getheavy.com/wp-content/uploads/2019/12/spotify2019-830x350.jpg"
alt=""
/>
<SidebarOption Icon={HomeIcon} title="Home" />
<SidebarOption Icon={SearchIcon} title="Search" />
<SidebarOption Icon={LibraryMusicIcon} title="Your Library" />
<br />
<strong className="sidebar__title">PLAYLISTS</strong>
<hr />
{playlists?.items?.forEach(playlist => {
<SidebarOption title={playlist.name} />
})}
</div>
)
}
ForEach将只循环通过一个数组,而映射将返回一个具有修改值的新数组。
render方法总是需要一个返回的JSX来进行渲染,而在forEach的情况下则无法获得。
render () {
//correct way
return items.map((item,index) =>
<SidebarOption title={item.name} key={index} />)
// returns modified/maped items JSX
}
render () {
return items.forEach((item,index) =>
<SidebarOption title={item.name} key={index} />)
// returns undefined
}
您需要使用map
而不是forEach
,因为map
返回一个数组。
{playlists?.items?.map((playlist, index) => {
<SidebarOption title={playlist.name} key={index} />
})}