我正在学习 ReactJS,并在尝试将 Youtube API 数据渲染到组件中时,我偶然发现了以下警告和错误。我试图了解它们背后的原因,但我对发生的事情一无所知。
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of
App
.Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of
App
.Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of
App
.Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of
App
.Uncaught TypeError: Cannot read property 'props' of undefined
我正在使用的有问题的代码如下。我确信这与我的 App 组件以及我如何设置 props 对象有关,但我无法查明问题的根源。
index.js
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import SearchBar from './components/search_bar';
import YTSearch from 'youtube-api-search';
import VideoList from './components/video_list';
const API_KEY = "not showing the real key here for obvious reasons";
class App extends Component {
constructor(props){
super(props);
this.state = {videos: []};
YTSearch({key: API_KEY, term: 'sufboards'}, (videos) => {
this.setState({videos});
});
}
render(){
return (
<div>
<SearchBar />
<VideoList videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector(".container"));
video_detail.js
import React from 'react';
const VideoList = (props) => {
return (
<ul className="col-md-4 list-group">
{props.videos.length}
</ul>
);
};
export default VideoList;
search_bar.js
import React, {Component} from 'react';
class SearchBar extends Component {
constructor(props){
super(props);
this.state = {term: ""};
}
render(){
return (
<input
onChange={
event => this.setState({
term: event.target.value
})
}
value = {this.state.term}
/>
);
}
}
export default SearchBar;
最佳答案
简单修复:
从“./components/video_list”导入VideoList;
该文件为空,我的代码位于 video_detail.js
中,因此我必须将其移动到正确的文件 video_list.js
关于javascript - 在我的组件中 react 不变违规错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36902612/