React JS-未捕获的TypeError:this.props.data.map不是函数

JavaScript

NearPro

2020-03-12

I'm working with reactjs and cannot seem 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:

未捕获的TypeError:无法读取未定义的属性“ map”

这是sessions.json:

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

第1121篇《React JS-未捕获的TypeError:this.props.data.map不是函数》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
斯丁卡卡西 2020.03.12

componentDidMount()在获取数据时尝试生命周期

Stafan村村达蒙 2020.03.12

发生这种情况是因为在异步数据到达之前就已经渲染了组件,因此应该在渲染之前进行控制。

我以这种方式解决了它:

render() {
    let partners = this.props && this.props.partners.length > 0 ?
        this.props.partners.map(p=>
            <li className = "partners" key={p.id}>
                <img src={p.img} alt={p.name}/> {p.name} </li>
        ) : <span></span>;

    return (
        <div>
            <ul>{partners}</ul>
        </div>
    );
}
  • 当属性为null / undefined时地图无法解析,所以我先做了一个控件

this.props && this.props.partners.length > 0 ?

卡卡西小宇宙 2020.03.12

您不需要数组即可执行此操作。

var ItemNode = this.state.data.map(function(itemData) {
return (
   <ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
 );
});
Gil蛋蛋Tony 2020.03.12

对我有用的是将props.data使用转换为数组, data = Array.from(props.data); 然后可以使用该data.map()函数

阿飞蛋蛋 2020.03.12

通常,您还可以将新数据转换为数组,并使用类似concat的方法:

var newData = this.state.data.concat([data]);  
this.setState({data: newData})

这种模式实际上在https://facebook.github.io/react/的 Facebook ToDo演示应用程序中使用(请参阅“应用程序”一节)

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android