本文介绍了React JS中的未定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到以下错误:
Uncaught ReferenceError: videos2 is not defined
在此应用中:
class App extends Component {
constructor(props) {
super(props)
this.state = {
videos2:[],
selectedVideo:null
}
this.DMSearch()
}
DMSearch(){
fetch("https://api.dailymotion.com/videos?fields=description,id,thumbnail_url,title,&limit=5&search=cars")
.then(response => response.json())
.then(data=>this.setState({
videos2:data.videos2,
selectedVideo:videos2[0]}))
console.log(videos2)
}
render () {
const {videos2}=this.state
return (
<div>
<SearchBar onSearchTermChange= {DMSearch}/>
<VideoDetail video={this.state.selectedVideo}/>
<VideoList
onVideoSelect={selectedVideo=>this.setState({selectedVideo})}
videos2={this.state.videos2}/>
</div>
)
}
}
因此,我想知道我应该在哪里定义video2,而不是已经定义的地方.任何人都可以指出可能导致该错误的组件部分吗?
Therefore Im wondering where should I define videos2 apart from where it is defined already. Anyone could point me out to the part of the component that might be causing the error?
实际上,它与api json的成形方式有关.这是从json获取列表的正确方法:
Actually it had to do with the way api json was shaped.This is the proper way to fetch the list from json:
this.setState({
videos2: videos2.list,
selectedVideo: videos2[0]
});
推荐答案
在DMSearch中,videos2
未定义.
In DMSearch, videos2
is undefined.
DMSearch() {
fetch("https://api.dailymotion.com/videos?fields=description,id,thumbnail_url,title,&limit=5&search=cars")
.then(response => response.json())
.then(data => {
let videos2 = data.videos2; //define it here
this.setState({
videos2: videos2,
selectedVideo: videos2[0] // <-- this line will throw error
})
})
console.log(videos2) // <-- and this too
}
这篇关于React JS中的未定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!