How does React read JSON data?

In React, you can use the fetch function to send a request and retrieve data from a JSON file. Here is an example code:

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;

In the code above, we use the fetch function to send a GET request to read the data.json file. Next, we use the .json() method to parse the response into JSON format data and store it in a state called data. Finally, we use the map function to iterate through the data array and render the title and description of each item on the page.

Please note that the above code is a functional component that utilizes React’s Hooks API (useState and useEffect). Using functional components and Hooks API is the latest recommended practice in React.

bannerAds