react怎么读取json数据

2024-01-19,

React中读取JSON数据可以使用fetch函数来发送请求并获取数据。以下是一个示例代码:

import React, { useState, useEffect } from 'react';

const MyComponent = () => {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch('data.json') // 读取data.json文件
      .then(response => response.json()) // 将响应解析为JSON格式
      .then(jsonData => setData(jsonData)) // 将JSON数据存储到状态中
      .catch(error => console.error(error)); // 处理请求错误
  }, []);

  return (
    <div>
      {data.map(item => (
        <div key={item.id}>
          <h2>{item.title}</h2>
          <p>{item.description}</p>
        </div>
      ))}
    </div>
  );
};

export default MyComponent;

在上述代码中,我们使用fetch函数发送GET请求来读取data.json文件。然后,我们使用.json()方法将响应解析为JSON格式的数据,并将其存储到名为data的状态中。最后,我们使用map函数遍历data数组,并将每个item的titledescription渲染到页面上。

请注意,上述代码是一个函数组件,使用了React的Hooks API(useState和useEffect)。使用函数组件和Hooks API是React的最新推荐用法。

《react怎么读取json数据.doc》

下载本文的Word格式文档,以方便收藏与打印。