我與reactjs工作似乎並不能試圖顯示JSON數據(來自文件或服務器)時,爲防止此錯誤:陣營JS - 遺漏的類型錯誤:this.props.data.map不是一個函數
Uncaught TypeError: this.props.data.map is not a function
我看:
React code throwing 「TypeError: this.props.data.map is not a function」
React.js this.props.data.map() is not a function
這些都不幫我解決這個問題。在我的頁面加載後,我可以驗證this.data.props不是未定義的(並且具有與json對象相同的值 - 可以使用window.foo
調用),因此它看起來好像在調用它時沒有及時加載由ConversationList。我如何確保map
方法適用於json數據而不是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')
);
}
})
編輯:加樣conversations.json
注 - 調用this.props.data.conversations
也將返回一個錯誤:
var conversationNodes = this.props.data.conversations.map...
回報
Uncaught TypeError: Cannot read property 'map' of undefined
這裏是conversations.json:
{ 「user_has_unread_messages」:假 「unread_messages_count」:0, 「會話」:[{ 「ID」:18768 「last_message_snippet」: 「Lorem存有」, 「other_user_id」:10193}]}
可以嗎發佈示例conversations.json? – user120242
已添加。非常感謝! – keypulsations
我已經更新了答案。此外,還有一些建議:向ConversationList添加propTypes:{data:React.PropTypes.array}以驗證數據的類型,並在ConversationBox中添加一個componentWillUnmount:fn(),即「clearInterval」間隔。 – user120242