React JS - 未捕获的类型错误:this.props.data.map 不是函数 [英] React JS - Uncaught TypeError: this.props.data.map is not a function

查看:30
本文介绍了React JS - 未捕获的类型错误:this.props.data.map 不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 reactjs 并且在尝试显示 JSON 数据(来自文件或服务器)时似乎无法阻止此错误:

未捕获的类型错误:this.props.data.map 不是函数

我看过:

反应代码抛出TypeError": this.props.data.map 不是函数"

React.js this.props.data.map() 不是函数

这些都没有帮助我解决问题.在我的页面加载后,我可以验证 this.data.props 不是未定义的(并且确实具有与 JSON 对象等效的值 - 可以使用 window.foo 调用),所以它似乎不是' 被 ConversationList 调用时没有及时加载.我如何确保 map 方法正在处理 JSON 数据而不是 undefined 变量?

var converter = new Showdown.converter();var 对话 = React.createClass({渲染:函数(){var rawMarkup = converter.makeHtml(this.props.children.toString());返回 (<div className="conversation panel panel-default"><div className="panel-heading"><h3 className="panel-title">{this.props.id}{this.props.last_message_snippet}{this.props.other_user_id}

<div className="panel-body"><span risklySetInnerHTML={{__html: rawMarkup}}/>

);}});var ConversationList = React.createClass({渲染:函数(){window.foo = this.props.data;var sessionNodes = this.props.data.map(function(conversation, index) {返回 (<会话id={conversation.id} key={index}>last_message_snippet={conversation.last_message_snippet}other_user_id={conversation.other_user_id}</对话>);});返回 (<div className="conversationList">{会话节点}

);}});var ConversationBox = React.createClass({loadConversationsFromServer: function() {返回 $.ajax({网址:this.props.url,数据类型:'json',成功:功能(数据){this.setState({数据: 数据});}.bind(this),错误:函数(xhr,状态,错误){console.error(this.props.url, status, err.toString());}.绑定(这个)});},getInitialState:函数(){返回{数据:[]};},componentDidMount:函数(){this.loadConversationsFromServer();setInterval(this.loadConversationsFromServer, this.props.pollInterval);},渲染:函数(){返回 (<div className="conversationBox"><h1>对话</h1><ConversationList data={this.state.data}/>

);}});$(document).on("page:change", function() {var $content = $("#content");如果($content.length > 0){反应.render(<ConversationBox url="/conversations.json" pollInterval={20000}/>,document.getElementById('内容'));}})

添加示例对话.json

注意 - 调用 this.props.data.conversations 也会返回错误:

var talkNodes = this.props.data.conversations.map...

返回以下错误:

<块引用>

未捕获的类型错误:无法读取未定义的属性 'map'

这是对话.json:

{"user_has_unread_messages":false,"unread_messages_count":0,"conversations":[{"id":18768,"last_message_snippet":"Lorem ipsum","other_user_id":10193}]}

解决方案

.map 函数仅适用于数组.
看起来 data 不是您期望的格式(它是 {},但您期望的是 []).

this.setState({data: data});

应该是

this.setState({data: data.conversations});

检查正在设置的数据"类型,并确保它是一个数组.

带有一些建议的修改代码(propType 验证和 clearInterval):

var converter = new Showdown.converter();var 对话 = React.createClass({渲染:函数(){var rawMarkup = converter.makeHtml(this.props.children.toString());返回 (<div className="conversation panel panel-default"><div className="panel-heading"><h3 className="panel-title">{this.props.id}{this.props.last_message_snippet}{this.props.other_user_id}

<div className="panel-body"><span risklySetInnerHTML={{__html: rawMarkup}}/>

);}});var ConversationList = React.createClass({//确保 this.props.data 是一个数组道具类型:{数据:React.PropTypes.array.isRequired},渲染:函数(){window.foo = this.props.data;var sessionNodes = this.props.data.map(function(conversation, index) {返回 (<会话id={conversation.id} key={index}>last_message_snippet={conversation.last_message_snippet}other_user_id={conversation.other_user_id}</对话>);});返回 (<div className="conversationList">{会话节点}

);}});var ConversationBox = React.createClass({loadConversationsFromServer: function() {返回 $.ajax({网址:this.props.url,数据类型:'json',成功:功能(数据){this.setState({data: data.conversations});}.bind(this),错误:函数(xhr,状态,错误){console.error(this.props.url, status, err.toString());}.绑定(这个)});},getInitialState:函数(){返回{数据:[]};},/* 取自https://facebook.github.io/react/docs/reusable-components.html#mixins卸载组件后清除所有间隔*/componentWillMount:函数(){this.intervals = [];},设置间隔:函数(){this.intervals.push(setInterval.apply(null, arguments));},componentWillUnmount:函数(){this.intervals.map(clearInterval);},componentDidMount:函数(){this.loadConversationsFromServer();this.setInterval(this.loadConversationsFromServer, this.props.pollInterval);},渲染:函数(){返回 (<div className="conversationBox"><h1>对话</h1><ConversationList data={this.state.data}/>

);}});$(document).on("page:change", function() {var $content = $("#content");如果($content.length > 0){反应.render(<ConversationBox url="/conversations.json" pollInterval={20000}/>,document.getElementById('内容'));}})

I'm working with reactjs and cannot seem to prevent this error when trying to display JSON data (either from file or server):

Uncaught TypeError: this.props.data.map is not a function

I've looked at:

React code throwing "TypeError: this.props.data.map is not a function"

React.js this.props.data.map() is not a function

Neither of these has helped me fix the problem. After my page loads, I can verify that this.data.props is not undefined (and does have a value equivalent to the JSON object - can call with window.foo), so it seems like it isn't loading in time when it is called by ConversationList. How do I make sure that the map method is working on the JSON data and not an undefined variable?

var converter = new Showdown.converter();

var Conversation = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="conversation panel panel-default">
        <div className="panel-heading">
          <h3 className="panel-title">
            {this.props.id}
            {this.props.last_message_snippet}
            {this.props.other_user_id}
          </h3>
        </div>
        <div className="panel-body">
          <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
        </div>
      </div>
    );
  }
});

var ConversationList = React.createClass({
  render: function() {

    window.foo            = this.props.data;
    var conversationNodes = this.props.data.map(function(conversation, index) {

      return (
        <Conversation id={conversation.id} key={index}>
          last_message_snippet={conversation.last_message_snippet}
          other_user_id={conversation.other_user_id}
        </Conversation>
      );
    });

    return (
      <div className="conversationList">
        {conversationNodes}
      </div>
    );
  }
});

var ConversationBox = React.createClass({
  loadConversationsFromServer: function() {
    return $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },
  componentDidMount: function() {
    this.loadConversationsFromServer();
    setInterval(this.loadConversationsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="conversationBox">
        <h1>Conversations</h1>
        <ConversationList data={this.state.data} />
      </div>
    );
  }
});

$(document).on("page:change", function() {
  var $content = $("#content");
  if ($content.length > 0) {
    React.render(
      <ConversationBox url="/conversations.json" pollInterval={20000} />,
      document.getElementById('content')
    );
  }
})

EDIT: adding sample conversations.json

Note - calling this.props.data.conversations also returns an error:

var conversationNodes = this.props.data.conversations.map...

returns the following error:

Uncaught TypeError: Cannot read property 'map' of undefined

Here is conversations.json:

{"user_has_unread_messages":false,"unread_messages_count":0,"conversations":[{"id":18768,"last_message_snippet":"Lorem ipsum","other_user_id":10193}]}

解决方案

The .map function is only available on array.
It looks like data isn't in the format you are expecting it to be (it is {} but you are expecting []).

this.setState({data: data});

should be

this.setState({data: data.conversations});

Check what type "data" is being set to, and make sure that it is an array.

Modified code with a few recommendations (propType validation and clearInterval):

var converter = new Showdown.converter();

var Conversation = React.createClass({
  render: function() {
    var rawMarkup = converter.makeHtml(this.props.children.toString());
    return (
      <div className="conversation panel panel-default">
        <div className="panel-heading">
          <h3 className="panel-title">
            {this.props.id}
            {this.props.last_message_snippet}
            {this.props.other_user_id}
          </h3>
        </div>
        <div className="panel-body">
          <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
        </div>
      </div>
    );
  }
});

var ConversationList = React.createClass({
 // Make sure this.props.data is an array
  propTypes: {
    data: React.PropTypes.array.isRequired
  },
  render: function() {

    window.foo            = this.props.data;
    var conversationNodes = this.props.data.map(function(conversation, index) {

      return (
        <Conversation id={conversation.id} key={index}>
          last_message_snippet={conversation.last_message_snippet}
          other_user_id={conversation.other_user_id}
        </Conversation>
      );
    });

    return (
      <div className="conversationList">
        {conversationNodes}
      </div>
    );
  }
});

var ConversationBox = React.createClass({
  loadConversationsFromServer: function() {
    return $.ajax({
      url: this.props.url,
      dataType: 'json',
      success: function(data) {
        this.setState({data: data.conversations});
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  getInitialState: function() {
    return {data: []};
  },

 /* Taken from 
    https://facebook.github.io/react/docs/reusable-components.html#mixins
    clears all intervals after component is unmounted
  */
  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.map(clearInterval);
  },

  componentDidMount: function() {
    this.loadConversationsFromServer();
    this.setInterval(this.loadConversationsFromServer, this.props.pollInterval);
  },
  render: function() {
    return (
      <div className="conversationBox">
        <h1>Conversations</h1>
        <ConversationList data={this.state.data} />
      </div>
    );
  }
});

$(document).on("page:change", function() {
  var $content = $("#content");
  if ($content.length > 0) {
    React.render(
      <ConversationBox url="/conversations.json" pollInterval={20000} />,
      document.getElementById('content')
    );
  }
})

这篇关于React JS - 未捕获的类型错误:this.props.data.map 不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆