【发布时间】:2017-04-26 18:10:37
【问题描述】:
我正在尝试进行 AJAX 调用以将服务器数据导入我的 React 组件。
我无法使用 React 显示它。我收到此错误:
Uncaught TypeError: Cannot read property 'map' of undefined
我已经完成了 http://andrewhfarmer.com/react-ajax-best-practices/ 和 reactjs - Uncaught TypeError: Cannot read property 'map' of undefined 的研究;但是,我不确定如何将其映射到我的反应组件。
下面是我的代码:
var items;
$.get("http://localhost:3000/getProducts", function( data ) {
items = data;
this.state.items = data;
});
/*React Code Below */
var RepeatModule = React.createClass({
getInitialState: function() {
return { items: [] }
},
render: function() {
var listItems = this.props.items.map(function(item) {
return (
<div className='brick'>
<div>
<a target='_blank' href={item.productURL}><img src={item.imageURL}/></a>
<p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
<p className='storeName'>Nike Factory Store</p>
<img className='foundPicture' src='../images/rohit.png'/>
</div>
</div>
);
});
return (
<div>
{listItems}
</div>
);
}
});
ReactDOM.render(<RepeatModule items={items} />,
document.getElementById('clothing-content'));
我的带有项目属性的 JSON 数组是有效的:
这是下面的数组:
[ { _id: 584d1e36a609b545b37611ac,
imageURL: 'http://ih1.redbubble.net/image.252113981.3904/ra,unisex_tshirt,x1350,fafafa:ca443f4786,front-c,30,60,940,730-bg,f8f8f8.u2.jpg',
productName: 'Drake',
productType: 'T-Shirts & Hoodies',
price: '$29.97',
productURL: 'http://www.redbubble.com/people/misfitapparel/works/22923904-drake?grid_pos=6&p=t-shirt',
__v: 0 } ]
为什么会出现这个错误?又该如何实施?
【问题讨论】:
-
@AndyRay 我的 get 请求应该在我的初始状态函数中吗?
标签: javascript jquery ajax node.js reactjs