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

在React中映射本地.json数据,附本地JSON文件示例

Mapping Local JSON Data in React (Using Your Apartment Data)

Hey there! Let's break down exactly how to render your apartment JSON data in a React component. I'll use your specific JSON structure to make this as straightforward as possible.

Step 1: Import Your Local JSON File

First, you can directly import your JSON file into your React component—React supports this out of the box. Just make sure the path to your JSON file is correct relative to your component.

// Import the JSON data (replace './apartments.json' with your actual file path)
import apartmentData from './apartments.json';

Step 2: Map Over the results Array

Your JSON has a top-level results key that holds an array of apartment objects. We'll extract this array and use React's map() method to render each apartment as a UI element.

Here's a complete component example:

import React from 'react';
import apartmentData from './apartments.json';

const ApartmentList = () => {
  // Extract the results array from the imported JSON
  const apartments = apartmentData.results;

  return (
    <div style={{ maxWidth: '800px', margin: '0 auto', padding: '20px' }}>
      <h1>Apartment Listings</h1>
      {/* Map over each apartment in the results array */}
      {apartments.map((apartment) => (
        // Always include a unique "key" prop (use the apartment's id here)
        <div 
          key={apartment.id} 
          style={{ border: '1px solid #eee', borderRadius: '8px', padding: '16px', marginBottom: '16px' }}
        >
          <h2 style={{ marginTop: 0 }}>{apartment.title}</h2>
          <p><strong>Location:</strong> {apartment.location}</p>
          <p>{apartment.description}</p>
        </div>
      ))}
      {/* Handle empty case (optional but good practice) */}
      {apartments.length === 0 && <p>No apartment listings available.</p>}
    </div>
  );
};

export default ApartmentList;

Key Things to Note

  • Unique key Prop: When using map() in React, you must provide a unique key for each rendered item. Your apartments have an id field, which is perfect for this—never use the array index as a key unless absolutely necessary.
  • Path Correctness: Double-check the path to your JSON file. If it's in a subfolder (like ./data/apartments.json), make sure the import reflects that.
  • Static vs Dynamic Data: Since this is local static data, importing it directly is the simplest approach. If you ever need to load JSON dynamically (e.g., from an API later), you could use fetch() or axios, but for local files, direct import works great.

内容的提问来源于stack exchange,提问作者Eik Hunter

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:44:08