简体   繁体   中英

Issue in fetch nested datas from JSON.file

I have this db.json file which I want to render only the years on the screen. Like: 1999, 2000, 2001 and etc.

JSON file:

  {
   "cronology":
      [   
           {
             "year": "1999",
             "description": "This is a description text"  
           },
           {
            "year": "2000",
            "description": "This is a description text"
           },
           {
            "year": "2001",
            "This is a description text"
           },
           {
            "year": "2002",
            "This is a description text"
        }
      ]
    }

I had tried this way how you can see in this react component below and it didn't work for me.

React Component file:

import React, { Component } from 'react'
import { Scrollbars } from 'react-custom-scrollbars'

var data = require('./db.json');

class Cronology extends Component {
  constructor(props) {
    super(props)
    this.state = {
      cronology: [],
      year: "",
      description: ""
    }
  }

  componentDidMount() {
    this.setState({
      cronology: data.cronology

    })
  }

  render() {
    return (
      <ul>
        {
          Objct.keys(this.state.cronology).map(
            (i) => {
              return <li>i.year</li>
          })                  
        }
      </ul>            
   }
}

export default Cronology;

The screen didn't show any rendered data and there isn't any error message too. How can I solve it?

use only map

render() {

  const cronology = this.state.cronology || []; // validate cronology

  return (
    <ul>
      {
        cronology.map(
        (i) => {
          return <li>i.year</li>
      })                  
    }
  </ul>            
}

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