在react js中访问json文件

时间:2018-05-08 15:00:14

标签: javascript json reactjs

这是我的代码:

class App extends Component {
  constructor() {
    super();
    this.state = {
      data: [
        {
          name: 'Jal Irani',
          imgURL: './man.jpg',
          hobbyList: ['Front-end Web Development', 'Back-end Web Development', 'Eating Free Food'],
        },
      ],
    };
  }
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to Profiler</h1>
        </header>
        <p className="App-intro">//access the json data here</p>
      </div>
    );
  }
}

我想访问

中的json元素
<p className="App-intro">//access the json data here. 

我试图使用反应图功能但没有成功。

有任何帮助吗? AM new in react js。

3 个答案:

答案 0 :(得分:1)

您可以像这样呈现数据:

<p className="App-intro">
  <span>{this.state.data[0].name}</span>
  {this.state.data[0].hobbyList.map(e => <span key={e}>{e}</span>)}
</p>

答案 1 :(得分:1)

您是否尝试映射state data个对象?

render() {
 return (
  <div className="App">
    <header className="App-header">
      <img src={logo} className="App-logo" alt="logo" />
      <h1 className="App-title">Welcome to Profiler</h1>
    </header>

 {this.state.data.map((dataItem, i) => 
    <div key={i}>
      <span>{dataItem.name}</span>
      <img src={dataItem.imgURL}/>
      <ul>
        {dataItem.hobbyList.map((item, i) => <li key={i}>{item}</li>)}
      </ul>
    </div>
  )}
  </div>
);
}

答案 2 :(得分:1)

import React from "react";
class App extends React.Component {
  constructor() {
    super();
    this.state = {
      data: [
        {
          name: "Jal Irani",
          imgURL: "./man.jpg",
          hobbyList: [
            "Front-end Web Development",
            "Back-end Web Development",
            "Eating Free Food"
          ]
        }
      ]
    };
  }

  render() {
    const { name, imgURL, hobbyList } = this.state.data[0];
    console.log(name);
    console.log(imgURL);
    console.log(hobbyList);
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to Profiler</h1>
        </header>
        <p className="App-intro" />
      </div>
    );
  }
}