访问对象内部的数组
2018-12-19
63
我有一个可以渲染对象值的功能组件
const MovieItemDetails = (props) => {
return <div className='item-details'>
<div>
<img key={props.movieDetails.id} src={`https://image.tmdb.org/t/p/w1280${props.movieDetails.backdrop_path}`} alt={props.movieDetails.title} className='header-item-image' />
<a href='#t' className='header-item-name'>{props.movieDetails.title}</a>
<img src={`https://image.tmdb.org/t/p/w185/${props.movieDetails.poster_path}`} alt={props.movieDetails.title} className='header-item-poster' />
<h2>{props.movieDetails.genres[0].name}</h2>
</div>
</div>
}
我想要的是第一个数组的类型名称,我尝试过 {
props.movieDetails.genres[0].name>
但我得到了“TypeError:无法读取未定义的属性‘0’”
2个回答
与其一次又一次地引用嵌套数组,不如在开始时将其提取到 const 中,并在渲染之前检查其值。请参见下文:
const MovieItemDetails = (props) => {
const {movieDetails} = {...props};
return (movieDetails && movieDetails.genres ? <div className='item-details'>
<div>
<img key={movieDetails.id} src={`https://image.tmdb.org/t/p/w1280${movieDetails.backdrop_path}`} alt={movieDetails.title} className='header-item-image' />
<a href='#t' className='header-item-name'>{movieDetails.title}</a>
<img src={`https://image.tmdb.org/t/p/w185/${movieDetails.poster_path}`} alt={movieDetails.title} className='header-item-poster' />
<h2>{movieDetails.genres[0].name}</h2>
</div>
</div> : null);
}
Manu
2018-12-19
我建议以正确的方式调用它。请看以下代码。
import React from 'react'
import Header from './Header'
import Main from './Main'
const MovieItemDetails = (props) => {
return <div className='item-details'>
<div>
<img key={props.movieDetails.id} src= {`https://image.tmdb.org/t/p/w1280${props.movieDetails.backdrop_path}`} alt= {props.movieDetails.title} className='header-item-image' />
<a href='#t' className='header-item-name'>{props.movieDetails.title}</a>
<img src={`https://image.tmdb.org/t/p/w185/${props.movieDetails.poster_path}`} alt={props.movieDetails.title} className='header-item-poster' />
<h2>{props.movieDetails.genres[0].name}</h2>
</div>
</div>
}
const movieDetails = {
id: 1,
title: 'Movie',
genres : [
{id: 0, name : 'Songs'}
]
}
const App = () => (
<div>
<MovieItemDetails movieDetails={movieDetails} />
{MovieItemDetails({movieDetails})}
</div>
)
导出默认应用程序
Vishal Kumar
2018-12-19