[英]map function not working in React
I am new to React JS, I was testing out some functions in fiddler. 我是React JS的新手,我正在测试fiddler中的一些函数。 I am not sure why I get an error pointing to the map function.
我不知道为什么我得到一个指向map函数的错误。 I am not able to render the array i defined.
我无法渲染我定义的数组。
Relevant snippet: 相关片段:
{this.props.data.productSpecs.map(function(productSpec){
<b>Category Name:</b> {productSpec};
})}
Full code: 完整代码:
var productCategory = {
productName: 'SamamgaTV1',
productCategory: 'Television',
productSpecs: ['32inch','black','hd']
};
var ProductComponent = React.createClass({
render: function() {
return( <div>
<h2>Product</h2>
<b>Product Name:</b> {this.props.data.productName}
<h2>Category</h2>
<b>Category Name:</b> {this.props.data.productCategory}
<h2>Specs</h2>
{this.props.data.productSpecs.map(function(productSpec){
<b>Category Name:</b> {productSpec};
})}
</div>);
}
});
ReactDOM.render(
<ProductComponent data={productCategory} />,
document.getElementById('container')
);
First you missed to return
, then you must return ONE element. 首先你错过了
return
,然后你必须返回一个元素。 Here you return a <p>
and a TextNode
在这里,您返回
<p>
和TextNode
Moreover you need to provide a unique key. 此外,您需要提供一个独特的密钥。
Try with this : 试试这个:
{this.props.data.productSpecs.map(function(productSpec, i){
return <span key={i}><b>Category Name:</b> {productSpec}</span>;
})}
You need to return value from map
handler. 您需要从
map
处理程序返回值。
{this.props.data.productSpecs.map(function(productSpec){
return (<span><b>Category Name:</b> {productSpec}<span>);
})}
If you do not want to (or can't in some situations) wrap content in span, you can create & return fragment (very handy) 如果你不想(或者在某些情况下不能)在span中包装内容,你可以创建并返回片段(非常方便)
const createFragment = require('react-addons-create-fragment');
{this.props.data.productSpecs.map(function(productSpec){
return createFragment({
bold: <b>Category Name:</b>,
spec: productSpec,
});
})}
可能是您正在使用字符串,因此您必须使用split方法并传入一个空字符串,例如myValue.split('')。map();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.