React JS - Uncaught TypeError: this.props.data.map 不是一个函数
2022-08-30 02:07:01
我正在使用reactjs,并且在尝试显示JSON数据(来自文件或服务器)时似乎无法防止此错误:
Uncaught TypeError: this.props.data.map is not a function
我看过:
React 代码抛出 “TypeError: this.props.data.map is not a function”
React.js this.props.data.map() 不是一个函数
这些都没有帮助我解决问题。在我的页面加载后,我可以验证 this.data.props 不是未定义的(并且确实有一个等同于 JSON 对象的值 - 可以调用 ),所以当它被 ConversationList 调用时,它似乎没有及时加载。如何确保该方法处理的是 JSON 数据而不是变量?window.foo
map
undefined
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')
);
}
})
编辑:添加示例对话.json
注意 - 调用还会返回错误:this.props.data.conversations
var conversationNodes = this.props.data.conversations.map...
返回以下错误:
未捕获的类型错误:无法读取未定义的属性“映射”
以下是 conversations.json:
{"user_has_unread_messages":false,"unread_messages_count":0,"conversations":[{"id":18768,"last_message_snippet":"Lorem ipsum","other_user_id":10193}]}