我有一个呈现对象值的功能组件
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”
答案 0 :(得分:1)
与其一次又一次地引用嵌套数组,不如从一开始就将其提取为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);
}
答案 1 :(得分:0)
我宁愿以正确的方式称呼它。请看下面的代码。
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>
)
导出默认应用