React:从本地 JSON 文件加载和显示数据

这篇实用、简洁的文章向您展示了如何在 React 中从本地 JSON 文件加载和呈现数据。事不宜迟,让我们开始吧。

导入本地 JSON 文件

在使用create-react-app 创建的 React 项目中,您可以将本地 JSON 文件作为常规 ES 模块导入:

import data from './data.json';

导入的东西将是一个 Javascript 对象,而不是 JSON 字符串。因此,您不必调用JSON.parse() 方法。例如,如果您导入包含以下内容的 JSON 文件:

{
   "id": 1,
   "username": "KindaCode.com"
}

你会得到这个 Javascript 对象:

{id: 1, username: 'KindaCode.com'}

完整示例

虚拟数据

这是我们将用于示例的 JSON 数据:

{
    "posts": [
        {
            "id": 1,
            "title": "Post 1",
            "content": "Welcome to KindaCode.com. This is the full content of post 1"
        },
        {
            "id": 2,
            "title": "Post 2",
            "content": "This is the full content of post 2"
        },
        {
            "id": 3,
            "title": "Post 3",
            "content": "This is the full content of post 3"
        },
        {
            "id": 4,
            "title": "Post 4",
            "content": "This is the full content of post 4"
        }
    ]
}

应用预览

下面是我们将要构建的内容:一个简单的 React 应用程序,它呈现博客文章列表:

React:从本地 JSON 文件加载和显示数据

编写代码

  1. 为了确保我们有相同的起点,你应该初始化一个新的 React 项目:
npx create-react-app kindacode-example
  1. 在项目的“src”文件夹中,创建一个名为“data.json”的新文件。将您之前看到的虚拟数据添加到此文件中:

React:从本地 JSON 文件加载和显示数据

  1. 将“App.js”中的所有默认代码替换为以下内容:
// KindaCode.com
// src/App.js
import './App.css';

// import JSON data from data.json
import data from './data.json';

function App() {
  const posts = data.posts;

  return (
    <>
      <div className='container'>
        <h1>Blog Posts</h1>
        <div className='posts'>
          {posts.map((post) => (
            <div className='post' key={post.id}>
              <h2 className='title'>{post.title}</h2>
              <p className='content'>{post.content}</p>
            </div>
          ))}
        </div>
      </div>
    </>
  );
}

export default App;
  1. 这是 CSS 代码:
/* 
KindaCode.com
App.css 
*/

.container {
  width: 80%;
  margin: 30px auto;
}

h1 {
  display: inline-flex;
  padding: 10px 30px;
  background: #2196f3;
  color: #fff;
}
  1. 启动并运行:
npm start

最后,访问 http://localhost:3000 查看结果

结论

你已经学习了如何在 React 中获取和渲染本地 JSON 数据。该方法本身并不难,但在许多场景中都非常有用,例如当您需要构建一个没有频繁数据更新的小型 Web 应用程序并且您不想花费大量时间开发后端 API 时。