【问题标题】:TypeError: Cannot read property 'snippet' of undefinedTypeError:无法读取未定义的属性“片段”
【发布时间】:2017-09-12 11:37:14
【问题描述】:

我有以下两个课程。我认为这里的主要问题是渲染函数传递了初始状态,而不是在 YTsearch API 的帮助下更新的更新状态。如果我在控制台上打印有关视频的信息,我确实会收到有关对象搜索查询的相关信息。但是当将这些对象传递给一个新的组件(标题)时,它似乎是未定义的(null)。

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Component } from 'react';
import Youtube from './Youtube';
import Title from './Title';
import YTSearch from 'youtube-api-search';

const key = '************************************';

class YoutubeVideo extends React.Component {
  constructor(props) {
    super(props);
    this.state = {video:'', selectedVideo:'', received: false};
    this.getvideos();
  }

  getvideos() {
    YTSearch({key: key, term: 'football'}, (videos) => {
        this.setState({
            videos: videos,
            selectedVideo: videos[0],
            received : true
            });
        });
  }

  render() {
        if (this.state.received){
            return (
                <Title videoTitle={ this.state.selectedVideo }/>
            )
        }
        return (
            <div>
            </div>
        )
  }
}

ReactDOM.render(
    <YoutubeVideo />,
    document.getElementById('root')
);

Title.js

import React, { Component } from 'react';


class Title extends Component {

    render () {
    const video = this.props.videoTitle;
        return (
            <div>
                <div>{ this.video.snippet }</div>
                <div>{ this.video.snippet }</div>
            </div>
        )
    }
}

export default Title;

我在 Title.js 中收到以下错误:

TypeError: Cannot read property 'snippet' of undefined

请帮忙。

【问题讨论】:

  • 不要将状态中selectedVideo的初始值定义为空白字符串,而是将其定义为空白对象,例如:selectedVideo: {},它应该是{video.snippet}而不是this.video.snippet。跨度>

标签: javascript api reactjs youtube


【解决方案1】:
  1. 在 Title.js 中,使用 {video.sn-p} 而不是 this.video.sn-p。
  2. 您可以使用 react 组件生命周期方法来调用 getvideos() 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-24
    相关资源
    最近更新 更多