简体   繁体   中英

es2015 map doesn't support array of object?

Created a jsbin to demo the error, you can see the error here https://jsbin.com/muhuxunome/1/edit

class Hello extends React.Component {
  render() {
    const normalizedStats = [
  {
    "name": "Confirmed",
    "count": 7
  },
  {
    "name": "Unprocessed",
    "count": 2
  },
  {
    "name": "Not Suitable",
    "count": 9
  },
  {
    "name": "Shortlisted",
    "count": 17
  }
];

    return(
            <div>
            normalizedStats.map(obj => 
                <li>{obj.name} ({obj.count})</li>
            )
            </div>
        )
  }
}

I got error of obj is not defined? I tried lodash's map it worked, not sure why map of es2015 has error here.

You forgot the "{}"

return (
    <div>
        {normalizedStats.map((obj, index) => {
            return <li key={index}>{obj.name} ({obj.count})</li>;
        })}
    </div>
);

You need to use curly braces whenever you want to do JavaScript interpolation in your JSX.

Change

normalizedStats.map(obj => 
  <li>{obj.name} ({obj.count})</li>
)

to

{normalizedStats.map(obj => 
  <li>{obj.name} ({obj.count})</li>
)}

Wrap the map result within {} . You need to do that in order to render your elements within JSX. Also ideally should be adding a key to the retuned JSX elements from map

 {normalizedStats.map(obj => 
            <li key={obj.name}>{obj.name} ({obj.count})</li>
        )}

Code with sorting

class Image extends React.Component {
  render(){
    return <img className="center" {...this.props} />;
  }
}

Image.propTypes = {
  src: React.PropTypes.string.isRequired
};

class Hello extends React.Component {
  render() {
    const normalizedStats = [
  {
    "name": "Confirmed",
    "count": 7
  },
  {
    "name": "Unprocessed",
    "count": 2
  },
  {
    "name": "Not Suitable",
    "count": 9
  },
  {
    "name": "Shortlisted",
    "count": 17
  }
];
   normalizedStats.sort(function(a, b) {return a.count - b.count})
    return(
            <div>
      {normalizedStats.map((obj) =>  {
              return <li key={obj.name}>{obj.name} ({obj.count})</li>
            }

            )}
            </div>
        )
  }
}

class App extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      name: 'JSBin'
    };
  }

  render() {
    return (<div className="app">
        <Hello />
      </div>);
  }
}

ReactDOM.render(<App />, document.getElementById('app'));

JSBIN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM