首页 > 解决方案 > React - Rendering an array of objects using Map

问题描述

I'm trying to render an array of objects using Map and so far I've only been able to render the first item to the browser.

I figured something's up with my .map function, but I don't know enough about React and JS to pinpoint the problem.

Here's my App.js file:

// import stuff is here

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      items: []
    };
    this.componentWillMount = this.componentWillMount.bind(this);
  }

  componentWillMount() {
    fetch('THE-JSON-URL-IS-HERE')
    .then(res => res.json())
    .then(data => {
      this.setState({ items: data });
    });

 render() {

const { items } = this.state;

return (
  <div className="App">

    { items.map((item, num) => {
        return (
          <div className="people">

            <div className="elem">
              <p key={num}>{item.elems}</p>   
            </div>     

              <p key={num}><strong>{item.name}</strong></p>
              <p key={num}><small>{item.title}</small></p>             

            <div className="hidden">
              <p key={num}><small>{item.email}</small></p>
              <p key={num}><small><strong>Office: </strong>{item.office}</small></p>
            </div>
            {/* <p>{item.manager}</p> */}
          </div>

        );
    })}        
  </div>
    );
  }
}

export default App;

And here's a sample of the JSON file:

[
  {
    "elems": "Pr",
    "name": "Abby Langdale",
    "title": "President",
    "email": "alangdale0@hubpages.com",
    "office": "Javanrud",
    "manager": [
      {
        "elems": "Vp",
        "name": "Johnnie Mouncey",
        "title": "Vice President",
        "email": "jmouncey0@cnet.com",
        "office": "Canto",
        "manager": [
          {
            "elems": "Vp",
            "name": "Concordia Burgwyn",
            "title": "VP Quality Control",
            "email": "cburgwyn0@dyndns.org",
            "office": "Zhoukou",
            "manager": [
              {
                "elems": "En",
                "name": "Prissie Sainsberry",
                "title": "Web Developer IV",
                "email": "psainsberry0@yellowbook.com",
                "office": "Tugu",
                "manager": null
              },

etc. Abby's info is all that I've rendered.

标签: javascriptarraysreactjsfunctionobject

解决方案


首先尝试展平阵列。您需要知道数组将拥有的最大级别数。展平后,您可以使用地图功能:

const flatItems = items.flat(3);    // flatten up to 3 levels
items.map((item, num) => {
        return ( <render your div> );
}

推荐阅读