【问题标题】:Error: Element type is invalid: expected a string React错误:元素类型无效:期望字符串 React
【发布时间】:2018-03-02 04:15:52
【问题描述】:

我正在尝试运行此代码,并希望有 5 li 具有相同的文本视频。相反,我得到了这个。请帮我解决它。我附上了所有的错误截图和代码。

它工作正常如果我只是试图打印数组的计数为 5,它工作正常。但是,如果我尝试以下代码,则会出现错误。它在终端中运行良好,没有错误,但这来自控制台并且没有按应有的方式打印视频 5 时间。

search_bar.js

import React, { Component } from 'react';

class SearchBar extends Component {

    constructor(props) {
        super(props);

        this.state = { term: '' };
    }

    render() {
        return (
            <div>
                <input
                    value={this.state.term}
                    onChange={event => this.setState({ term: event.target.value })} />
            </div>
        );
    }
}

export default SearchBar;

index.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';

const API_KEY = 'xxxxxxxxxxxxxxx'

class App extends Component {

    constructor(props) {
        super(props);

        this.state = { videos: [] };

        YTSearch({ key: API_KEY, term: 'trump' }, (videos) => {
            this.setState({ videos });
        });
    }

    render() {
        return (
            <div>
                <SearchBar />
                <VideoList videos={this.state.videos} />
            </div>
        );
    }
}


//Take this component's generated HTML and put it on the page.(in the DOM) 

ReactDOM.render(<App />, document.querySelector('.container'));

video_list.js

import React from 'react';
import VideoListItem from './video_list_item';

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

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

export default VideoList;

video_detail.js

import React from 'react';

const VideoListItem = (props) => {
    return <ul>Video</ul>
};

export default VideoListItem;

【问题讨论】:

  • 应该&lt;ul&gt;Video&lt;/ul&gt;&lt;li&gt;Video&lt;/li&gt; 吗?
  • 文件名是:video_detail.js,但是你导入的是import VideoListItem from './video_list_item';,对吗???我认为应该是:import VideoListItem from './video_detail';

标签: javascript reactjs ecmascript-6 redux


【解决方案1】:

这个错误:

 Element type is invalid: expected a string (for built-in components) or a class/function

通常是由于您的 import 语句而发生的。仔细检查导入语句。正如 Mayank Shukla 在 cmets 上提到的,您在导入语句中使用不同的文件名导入 VideoListItem。

您还需要在 VideoListItem 组件中返回 &lt;li&gt;Video&lt;/li&gt;

【讨论】:

    猜你喜欢
    • 2016-10-03
    • 2017-11-02
    • 2018-02-07
    • 2020-03-11
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多