You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React JS中访问JSON文件?附现有代码示例

Hey there! Let's get your React app set up to access a JSON file instead of hardcoding the data directly in your state. I'll walk you through two common approaches depending on your use case:


Approach 1: Import the JSON File Directly (for local static data)

This is the simplest method if your JSON file is part of your project's static assets.

First, create a new JSON file (let's call it profileData.json) in your project (same directory as App.js works fine) with your data:

[
  {
    "name": "Jal Irani",
    "imgURL": "./man.jpg",
    "hobbyList": [
      "Front-end Web Development",
      "Back-end Web Development",
      "Eating Free Food"
    ]
  }
]

Then update your App component to import this file and use it in state:

import React, { Component } from 'react';
import logo from './logo.svg'; // Keep your existing logo import
import profileData from './profileData.json'; // Import the JSON file

class App extends Component {
  constructor() {
    super();
    this.state = {
      data: profileData, // Use the imported JSON data directly
    };
  }

  render() {
    // Pull the first profile from your data array
    const [profile] = this.state.data;
    
    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>
        <div className="App-intro">
          <h2>{profile.name}</h2>
          <img src={profile.imgURL} alt={`${profile.name}'s profile`} />
          <h3>Hobbies:</h3>
          <ul>
            {profile.hobbyList.map((hobby, index) => (
              <li key={index}>{hobby}</li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}

export default App;

Approach 2: Fetch the JSON File (for remote/async data)

If your JSON file is hosted on a server or you need to load it asynchronously, use the fetch API. This is also useful if you're keeping the JSON in your public folder.

First, move your profileData.json to the public directory of your React project. Then update your component:

import React, { Component } from 'react';
import logo from './logo.svg';

class App extends Component {
  constructor() {
    super();
    this.state = {
      data: [],
      loading: true,
      error: null,
    };
  }

  componentDidMount() {
    // Fetch the JSON file from the public directory
    fetch('/profileData.json')
      .then(response => {
        if (!response.ok) {
          throw new Error('Could not load profile data');
        }
        return response.json();
      })
      .then(data => {
        this.setState({ data, loading: false });
      })
      .catch(error => {
        this.setState({ error: error.message, loading: false });
      });
  }

  render() {
    const { data, loading, error } = this.state;

    // Show loading state while data is fetched
    if (loading) return <div className="App-intro">Loading profile...</div>;
    // Show error if fetch fails
    if (error) return <div className="App-intro">Oops: {error}</div>;

    const [profile] = data;
    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>
        <div className="App-intro">
          <h2>{profile.name}</h2>
          <img src={profile.imgURL} alt={`${profile.name}'s profile`} />
          <h3>Hobbies:</h3>
          <ul>
            {profile.hobbyList.map((hobby, index) => (
              <li key={index}>{hobby}</li>
            ))}
          </ul>
        </div>
      </div>
    );
  }
}

export default App;

Quick Notes:

  • For the import method, double-check your file path to make sure React can find the JSON file.
  • When using fetch, files in the public folder are accessible via root paths (like /profileData.json).
  • I replaced your placeholder <p className="App-intro">//access ...</p> with actual rendered content so you can see the profile data displayed right away.

内容的提问来源于stack exchange,提问作者ngahu daniel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:20:54