【问题标题】:React JS - Uncaught TypeError: props.video.map is not a functionReact JS - 未捕获的 TypeError:props.video.map 不是函数
【发布时间】: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


【解决方案1】:

尝试将videos默认状态设置为空数组[]而不是对象{}:

this.state = { videos: [] };

发生此错误是因为map() 是一个数组方法,根本不适用于对象。

【讨论】:

  • 哇!就是这样。不敢相信我没看到!现在我知道下次去哪里检查了。非常感谢!
【解决方案2】:

试试这个方法。

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

也许 props.video 在渲染之前是未定义的。

【讨论】:

  • 感谢您的建议!我试过了,但我看到了同样的错误信息。
  • 我现在在问题中包含了另一个文件。谢谢!
猜你喜欢
  • 1970-01-01
  • 2015-07-20
  • 2022-08-10
  • 2016-05-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多