Javascript React JS - 未捕获的类型错误:this.props.data.map 不是函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30142361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
React JS - Uncaught TypeError: this.props.data.map is not a function
提问by keypulsations
I'm working with reactjs and cannot seem to prevent this error when trying to display JSON data (either from file or server):
我正在使用 reactjs 并且在尝试显示 JSON 数据(来自文件或服务器)时似乎无法防止此错误:
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 代码抛出“TypeError: this.props.data.map is not a function”
React.js this.props.data.map() is not a function
React.js this.props.data.map() 不是函数
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 mapmethod is working on the JSON data and not an undefinedvariable?
这些都没有帮助我解决问题。在我的页面加载后,我可以验证 this.data.props 不是未定义的(并且确实具有与 JSON 对象等效的值 - 可以使用 调用window.foo),因此它在被调用时似乎没有及时加载对话列表。如何确保该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')
);
}
})
EDIT: adding sample conversations.json
编辑:添加示例对话.json
Note - calling this.props.data.conversationsalso returns an error:
注意 - 调用this.props.data.conversations也会返回错误:
var conversationNodes = this.props.data.conversations.map...
returns the following error:
返回以下错误:
Uncaught TypeError: Cannot read property 'map' of undefined
未捕获的类型错误:无法读取未定义的属性“地图”
Here is conversations.json:
这是对话.json:
{"user_has_unread_messages":false,"unread_messages_count":0,"conversations":[{"id":18768,"last_message_snippet":"Lorem ipsum","other_user_id":10193}]}
回答by user120242
The .mapfunction is only available on array.
It looks like dataisn't in the format you are expecting it to be (it is {} but you are expecting []).
该.map函数仅适用于数组。
它看起来data不是您期望的格式(它是 {},但您期望的是 [])。
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):
修改了一些建议的代码(propType 验证和 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')
);
}
})
回答by Vishal Seshagiri
what worked for me is converting the props.data to an array using
data = Array.from(props.data);
then I could use the data.map()function
对我有用的是将 props.data 转换为数组,
data = Array.from(props.data);
然后我可以使用该data.map()函数
回答by bresson
More generally, you can also convert the new data into an array and use something like concat:
更一般地说,您还可以将新数据转换为数组并使用类似 concat 的内容:
var newData = this.state.data.concat([data]);
this.setState({data: newData})
This pattern is actually used in Facebook's ToDo demo app (see the section "An Application") at https://facebook.github.io/react/.
这种模式实际上在 Facebook 的 ToDo 演示应用程序中使用(请参阅https://facebook.github.io/react/ 上的“应用程序”部分)。
回答by CodeGuru
You don't need an array to do it.
你不需要一个数组来做到这一点。
var ItemNode = this.state.data.map(function(itemData) {
return (
<ComponentName title={itemData.title} key={itemData.id} number={itemData.id}/>
);
});
回答by J C
It happens because the component is rendered before the async data arrived, you should control before to render.
发生这种情况是因为组件在异步数据到达之前渲染,您应该在渲染之前进行控制。
I resolved it in this way:
我是这样解决的:
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>
);
}
- Map can not resolve when the property is null/undefined, so I did a control first
- 当属性为空/未定义时,地图无法解析,所以我先做了一个控件
this.props && this.props.partners.length > 0 ?
this.props && this.props.partners.length > 0 ?
回答by ISRAEL ODUGUWA
You need to convert the object into an array to use the mapfunction:
您需要将对象转换为数组才能使用该map函数:
const mad = Object.values(this.props.location.state);
where this.props.location.stateis the passed object into another component.
this.props.location.state传递给另一个组件的对象在哪里。
回答by Arif Ramadhani
try componentDidMount()lifecycle when fetching data
componentDidMount()获取数据时尝试生命周期

