首页 > 解决方案 > 从 JSON.file 获取嵌套数据的问题

问题描述

我有这个 db.json 文件,我只想在屏幕上呈现年份。如:1999、2000、2001 等。

JSON文件:

  {
   "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"
        }
      ]
    }

我已经尝试过这种方式,您可以在下面的这个反应组件中看到它,但它对我不起作用。

反应组件文件:

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;

屏幕没有显示任何渲染数据,也没有任何错误消息。我该如何解决?

标签: javascriptjsonreactjs

解决方案


只使用地图

render() {

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

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

推荐阅读