Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

javascript - map function not working in React

I am new to React JS, I was testing out some functions in fiddler. I am not sure why I get an error pointing to the map function. 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')
);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First you missed to return, then you must return ONE element. Here you return a <p> and a 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>;
})}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...