【发布时间】:2018-09-03 10:00:23
【问题描述】:
我是 React 新手,正在尝试调试我看到的以下错误。
错误 #1:
Uncaught TypeError: props.videos.map is not a function
at new VideoList
错误 #2:
bundle.js:19956 Error: findComponentRoot(..., .0.0.0): Unable to find element.
This probably means the DOM was unexpectedly mutated (e.g., by the browser),
usually due to forgetting a <tbody> when using tables, nesting tags like
<form>, <p>, or <a>, or using non-SVG elements in an <svg> parent.
Try inspecting the child nodes of the element with React ID ``.
这是我参考这个文件的代码:
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;
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 = '';
// create a new component. This component should produce
// some HTML
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: {} };
YTSearch({key: API_KEY, term: 'React'}, (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'));
我查看了关于 SOF 的以下问题,但都无法解决我的问题:
React JS - Uncaught TypeError: this.props.data.map is not a function
React.js this.props.data.map() is not a function
我很难理解的是为什么它给了我错误#1,因为我正在使用带有“胖箭头”的函数声明。我假设错误 #2 是错误 #1 的结果。
我做错了什么?
【问题讨论】:
-
尝试记录
props.videos并确保它是一个数组,甚至是一个空数组。如果它不是数组或未定义,则可能会发生此错误。 -
我正要问同样的事情:)
-
嗨@AlexanderStaroselsky!谢谢你的建议。我刚才确实尝试了
console.log(props.videos);,但它似乎没有在控制台中返回任何内容。 -
您是否在
VideoList正文中的const videoItems ...之前尝试过?目标是查看props或props.videos的结构和类型。如果不存在视频或类似的视频,您可能会通过默认视频绕过此错误到一个空数组。 -
map()是一个数组函数。它不能应用于对象。看起来您将videos默认为一个对象,而不是空数组[]。数据是否以数组形式出现?还是作为YTSearch中的对象?
标签: javascript reactjs