我已经在 React 中实现了一个小测试应用程序以通过 AJAX 获取数据,但它没有按预期工作,因此我收到以下错误:
Uncaught TypeError: Cannot read property 'map' of undefinedInline JSX script
代码如下:
<div id="content"></div>
<script type="text/jsx">
var Bodypart = React.createClass({
render: function() {
return (
<div>
{this.props.name}
</div>
)
}
})
var BodypartList = React.createClass({
getInitialState: function() {
return {data: []};
},
componentWillMount: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
success: function(data) {
this.setState({bodyparts: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function() {
var bodypartItems = this.state.bodyparts.map(function (bodypart) {
return (
<Bodypart
name={bodypart.name}
/>
);
});
return (
<div>
{bodypartItems}
</div>
);
}
});
React.render(
<BodypartList url="/api/bodyparts/" />,
document.getElementById('content')
);
</script>
来自/api/bodyparts/
的响应:
{
"bodyparts": [
{
"id": 1,
"name": "Face"
},
{
"id": 3,
"name": "Mouth"
},
{
"id": 2,
"name": "Nose"
}
]
}
最佳答案
在初始渲染时 this.state.bodyparts
是 undefined
因此出现错误。
你应该回来
{bodyparts:[]}
来自 getInitialState
。
同样在你的 success
回调中你应该设置这样的状态:
this.setState(data);
因为您的 api 已经返回 bodyparts
作为其结果的一部分。
关于javascript - 未捕获的类型错误 : Cannot read property 'map' of undefined with React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28630005/