React 导入 JSON 文件,将内容存储在 State 中并渲染出来

React import JSON file, store content in State and render it out

如何使用我的 JSON 数据更新状态,然后将其输出为列表项?

我想在 componentDidMount() 中使用 setState 函数,以便在页面加载时立即将数据存储在状态中并在页面上输出

import React from 'react';
import peopleData from '../persons.json';

class App extends React.Component {
  constructor(){
    super();
    this.state = {
      people: []
    }
  }

  componentDidMount(){
    console.log(peopleData);
  }

  render() {
    return (
      <div>
        <ul>
          //Loop out this.state.people.names here as List Items
        </ul>
      </div>
    )
  }
}

export default App;

这是我导入到上面的 JSON 数据。

[
 {
   "Name": "Lisa",
   "Age": 100
 },

 {
   "Name": "Bob",
   "Age": 44
 },

 {
   "Name": "Joe",
   "Age": 17
 },

 {
   "Name": "Jesper",
   "Age": 6
 }
]

你不能将 peopleData 指定为人物的默认状态吗属性?它的工作原理是一样的,而且更简洁。

class App extends React.Component {
  constructor(){
    super();
    this.state = {
      people: peopleData,
    }
  }

  render() {
    const list = this.state.people.map(d => <li>{p.Name} - {p.Age}</li>);
    return (
      <div>
        <ul>
          {list}
        </ul>
      </div>
    )
  }
}