map function not working in React

怎甘沉沦 提交于 2021-02-04 14:02:03

问题


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')
);

回答1:


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>;
})}



回答2:


You need to return value from map handler.

{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)

const createFragment = require('react-addons-create-fragment');

{this.props.data.productSpecs.map(function(productSpec){
    return createFragment({
        bold: <b>Category Name:</b>,
        spec: productSpec,
    });
})}



回答3:


It might be that you are using a string so you have to use the split method and pass in an empty string such as myValue.split('').map();



来源:https://stackoverflow.com/questions/39999671/map-function-not-working-in-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!