[英]How can I access API object properties in React?
I'm having trouble accessing an object using React. 我在使用React访问对象时遇到麻烦。 The object was generated using tMDB API. 该对象是使用tMDB API生成的。 Once I can access the object, I would like to pass the ID prop down to a child component. 一旦可以访问该对象,我想将ID属性传递给子组件。
Home: 家:
import React, {Component} from 'react'
import Movie from '../components/Movie'
import '../index.css'
class Home extends Component{
constructor(props) {
super(props)
this.state = {
movie: [],
}
}
componentDidMount() {
this.fetchData()
}
fetchData(){
fetch('https://api.themoviedb.org/3/movie/now_playing?api_key=17c21a1abd8ae7be6ee8986389011906')
.then(response=> response.json())
.then( ({results: movie}) => this.setState({movie}))
}
render() {
console.log(this.state.movie[1].id);
return(
<div className="main">
<div>
</div>
</div>
)
}
}
export default Home
This outputs TypeError: Cannot read property 'id' of undefined 这将输出TypeError:无法读取未定义的属性“ id”
If I change this.state.movie[1].id
to this.state.movie[1]
I can see the full object and it's properties, but cannot access child properties in the code. 如果将this.state.movie[1].id
更改为this.state.movie[1]
,则可以看到完整的对象及其属性,但是无法访问代码中的子属性。
I believe the problem might be that React is rendering the state twice since there is an 'undefined' object right above the movie object. 我相信问题可能是React两次渲染状态,因为在电影对象上方有一个“未定义”的对象。 If so, how could I fix that? 如果是这样,我该如何解决?
Console: 安慰:
Array(0)
length
:
0
__proto__
:
Array(0)
Home.js:26
Array(20)
0:
{vote_count: 4600, id: 284053, video: false, vote_average: 7.4, title: "Thor: Ragnarok", …}
1:
{vote_count: 2314, id: 284054, video: false, vote_average: 7.4, title: "Black Panther", …}
2:
{vote_count: 771, id: 337167, video: false, vote_average: 6.3, title: "Fifty Shades Freed", …}
...
You have to validate if movie is empty, as your api call takes some time to get a response. 您必须验证movie是否为空,因为您的api调用需要一些时间才能获得响应。 Keep in mind that react rerenders you component every time you modify your state using setState 请记住,每次使用setState修改状态时,react都会重新渲染您的组件
render() {
if (this.state.movie.length === 0) {
return (<div>Loading data...</div>)
}
console.log(this.state.movie[1].id);
return(
<div className="main">
<div>
</div>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.