【问题标题】:Undefined object in react js反应js中的未定义对象
【发布时间】:2018-06-23 14:55:47
【问题描述】:

我收到以下错误:

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。任何人都可以指出可能导致错误的组件部分?

编辑:实际上它与 api json 的形成方式有关。 这是从 json 中获取列表的正确方法:

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

【问题讨论】:

    标签: reactjs ecmascript-6


    【解决方案1】:

    DMSearch 函数中没有定义videos2 变量。你可能想要:

    .then(data => {
        this.setState({
           videos2: data.videos2, 
           selectedVideo: data.videos2[0]
        });
        console.log(data.videos2);
     });        
    

    .then(data => {
        const { videos2 } = data;
        this.setState({
           videos2,
           selectedVideo:videos2[0]
        });
        console.log(videos2);
     });  
    

    【讨论】:

      【解决方案2】:

      在 DMSearch 中,videos2 未定义。

      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
      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多