在React中访问嵌套的json

时间:2018-06-23 16:08:53

标签: reactjs ecmascript-6

我可以从api成功获取json对象。但是,更新状态似乎存在问题。 打印对象后,我得到了预期的期望结果console.log(videos2.list[0]);从json对象的list属性给出了第一项,您可以检查api在此链接下的外观: https://api.dailymotion.com/videos?fields=description,id,thumbnail_url,title,&limit=5&search=cars

但是,当使用setState属性selectedVideo更新状态时,视频:videos.list [0]未定义。

该组件的代码:

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(result => result.json())
    .then(videos2 => {
        console.log(videos2.list[0]);
        this.setState({
           videos2: videos2.list, 
           selectedVideo: videos2.list[0]
        });
        console.log(selectedVideo);
     });  
    }  
render () {
    const DMSearch = this.DMSearch()
    return (
        <div>
            <SearchBar onSearchTermChange= {DMSearch}/>
            <VideoDetail video={this.state.selectedVideo}/> 
            <VideoList 
            onVideoSelect={selectedVideo=>this.setState({selectedVideo})}
            videos2={this.state.videos2}/>
        </div>
    )
}
}  

确切的错误是Uncaught (in promise) ReferenceError: selectedVideo is not defined

videos2:list[0]产生正确的结果,但是当分配给selectedVideo时是undefined

根据要求,我还包括了vide_list的代码,该代码使用对象形式的父组件,这可能会在此处产生错误:

const VideoList = (props) => {

    const videoItems = props.videos.map((video)=>{
        return (
        <VideoListItem 
            onVideoSelect={props.onVideoSelect}
            key={video.etag} 
            video={video} />
        )
    })

    return (
        <ul className="col-md-4 list-group">
            {videoItems}
        </ul>
    )
}

具体来说,此行

const videoItems = props.videos.map((video)=> {

在读取道具时会导致错误。我相信这与selectedVideo为空...

有关

2 个答案:

答案 0 :(得分:0)

此行有问题

console.log(selectedVideo);

您已打印出未定义的变量。应该是this.state.selectedVideo。

答案 1 :(得分:-1)

发生错误selectedVideo is not defined是因为selectedVideo不是变量,它是传递给this.setState函数的javascript对象上的键。

//...
this.setState({
   videos2: videos2.list, 
   selectedVideo: videos2.list[0]
});
//...

您可以通过创建变量来减轻错误:

DMSearch(){
fetch(`https://api.dailymotion.com/videos?fields=description,id,thumbnail_url,title,&limit=5&search=cars`)
.then(result => result.json())
.then(videos2 => {
    console.log(videos2.list[0]);
    const selectedVideo = videos2.list[0]; // create variable
    this.setState({
       videos2: videos2.list, 
       selectedVideo: selectedVideo
    });
    console.log(selectedVideo);
 });  
}