在 React.js 中解析 JSON 数据

发布日期:2026-07-15 11:19:04   来源 : 杭州电子商务研究院    浏览量 :3
杭州电子商务研究院 发布日期:2026-07-15 11:19:04  
3

介绍

在前端开发中,JSON 数据不仅至关重要,而且几乎不可避免。React 开发人员与 JSON 数据密切相关,因此,了解如何读取、解析和操作 JSON 数据非常重要。JSON 数据可以来自许多来源,但最常见的是第三方API 和外部数据文件。

在本指南中,您将了解如何在 React.js 中解析 JSON 数据。我们假设您对 JSON 有很好的基础知识,并且至少具备React.js 的初级水平。

React.js 开发中的 JSON 数据

根据Mozilla的说法,“JSON 是一种基于 JavaScript 对象语法表示结构化数据的标准文本格式。”它完全独立于语言,因此在开发领域得到广泛使用。它主要用于在应用程序和服务器之间发送数据。

设置示例应用程序

打开你的终端并运行这些命令来创建一个基本的 React 应用程序。

      npx create-react-app react-json

cd react-json

npm start
    

源 JSON 数据

为了遵循本指南中的示例,您将从TMDB 电影数据库获取数据。您需要设置一个用户帐户以获取 API 密钥。

在 React 中解析 JSON

TMDB 为您提供 JSON 格式的电影、电视节目和演员及其图像列表。您需要解析这些数据并在您的应用中显示不同类型的电影或电视节目。为了获取数据,您将使用Axios,这是一个便于向外部源(在本例中为 TMDB API)发出 HTTP 请求的库。要安装 Axios,请在您的终端上运行以下命令。

      npm install axios
    

导航到您的App.js文件并粘贴下面的示例代码。

      import React, {Component} from 'react';
import axios from 'axios'

class App extends Component{
  constructor(props) {
    super(props);
    this.state =({
      movies: []
    })
  }
  componentDidMount() {
    let url = "https://api.themoviedb.org/3/discover/movie?api_key=abcdef123&sort_by=popularity.desc&page=1"
    axios.get(url)
        .then(response => {
          console.log(response.data.results)
            this.setState({
                movies: response.data.results
            })
        })
        .catch(error => {
          console.log(error)
        })
  }

  render() {
    return (
        <div>
        </div>
    );
  }

}

export default App;
    

您首先将初始化电影状态,其中包含来自 TMDB API 的数据。接下来,您将使用componentDidMount() ,这是一个 React 生命周期方法。此生命周期方法会立即调用,并且组件会被挂载。您可以在此处了解更多信息

在此方法中,您将使用 Axios 从 TMDB API 获取数据。确保您拥有有效的 API 密钥。URL 应从 TMDB 数据库获取热门电影列表。使用 API 的结果设置电影状态。在浏览器中转到 https://localhost:3000 并在控制台选项卡中检查数据。如果没有数据,您可能需要运行命令npm run start或刷新浏览器。

这是来自 API 的示例数据。

      {
	"page": 1,
	"results": [{
			"poster_path": "/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",
			"adult": false,
			"overview": "From DC Comics comes the Suicide Squad, an antihero team of incarcerated supervillains who act as deniable assets for the United States government, undertaking high-risk black ops missions in exchange for commuted prison sentences.",
			"release_date": "2016-08-03",
			"genre_ids": [
				14,
				28,
				80
			],
			"id": 297761,
			"original_title": "Suicide Squad",
			"original_language": "en",
			"title": "Suicide Squad",
			"backdrop_path": "/ndlQ2Cuc3cjTL7lTynw6I4boP4S.jpg",
			"popularity": 48.261451,
			"vote_count": 1466,
			"video": false,
			"vote_average": 5.91
		},
		{
			"poster_path": "/lFSSLTlFozwpaGlO31OoUeirBgQ.jpg",
			"adult": false,
			"overview": "The most dangerous former operative of the CIA is drawn out of hiding to uncover hidden truths about his past.",
			"release_date": "2016-07-27",
			"genre_ids": [
				28,
				53
			],
			"id": 324668,
			"original_title": "Jason Bourne",
			"original_language": "en",
			"title": "Jason Bourne",
			"backdrop_path": "/AoT2YrJUJlg5vKE3iMOLvHlTd3m.jpg",
			"popularity": 30.690177,
			"vote_count": 649,
			"video": false,
			"vote_average": 5.25
		},
		{
			"poster_path": "/hU0E130tsGdsYa4K9lc3Xrn5Wyt.jpg",
			"adult": false,
			"overview": "One year after outwitting the FBI and winning the public’s adulation with their mind-bending spectacles, the Four Horsemen resurface only to find themselves face to face with a new enemy who enlists them to pull off their most dangerous heist yet.",
			"release_date": "2016-06-02",
			"genre_ids": [
				28,
				12,
				35,
				80,
				9648,
				53
			],
			"id": 291805,
			"original_title": "Now You See Me 2",
			"original_language": "en",
			"title": "Now You See Me 2",
			"backdrop_path": "/zrAO2OOa6s6dQMQ7zsUbDyIBrAP.jpg",
			"popularity": 29.737342,
			"vote_count": 684,
			"video": false,
			"vote_average": 6.64
		}
	]

}
    

获取数据后,您需要解析 JSON 格式的数据并将其显示在您的应用中。对于这种方法,您将使用简单的 Bootstrap 卡片组件。React Bootstrap 为 React 应用提供了 Bootstrap 组件。在您的终端中运行npm install react-bootstrap bootstrap 。最后,在您的app.js文件中添加下面的示例代码

      import React, {Component} from 'react';
import axios from 'axios'
import 'bootstrap/dist/css/bootstrap.min.css';
import {Button, Card, Col, Row} from "react-bootstrap";


class App extends Component{
  constructor(props) {
    super(props);
    this.state =({
      movies: []
    })
  }
  componentDidMount() {
    let url = "https://api.themoviedb.org/3/discover/movie?api_key=b1422e7b80cff3571090be90e6544244";
    axios.get(url+"&sort_by=popularity.desc&page=1")
        .then(response => {
          console.log(response.data.results)
            this.setState({
                movies: response.data.results
            })
        })
        .catch(error => {
          console.log(error)
        })
  }

  render() {
    return (
        <Row>
            <Col>
                <Card style={{ width: '18rem' }}>
                    <Card.Img variant="top" src=""/>
                    <Card.Body>
                        <Card.Title>Card Title</Card.Title>
                        <Card.Text>
                            Some quick example text
                        </Card.Text>
                        <Button variant="primary">Go somewhere</Button>
                    </Card.Body>
                </Card>
            </Col>
        </Row>
        )
      }
}
export default App;
    

现在您已经设置了卡片组件,您需要解析电影状态中的 JSON 数据并设置卡片内的选定字段。您将使用一个名为map()的漂亮 JavaScript 方法。此方法使您能够迭代电影状态并获取字段所需的值。请记住,您的电影状态保存着您的 JSON 数据。

将下面的示例代码添加到您的app.js文件中。

      import React, {Component} from 'react';
import axios from 'axios'
import 'bootstrap/dist/css/bootstrap.min.css';
import {Button, Card, Col, Row} from "react-bootstrap";


class App extends Component{
  constructor(props) {
    super(props);
    this.state =({
      movies: []
    })
  }
  componentDidMount() {
    let url = "https://api.themoviedb.org/3/discover/movie?api_key=b1422e7b80cff3571090be90e6544244";
    axios.get(url+"&sort_by=popularity.desc&page=1")
        .then(response => {
          console.log(response.data.results)
            this.setState({
                movies: response.data.results
            })
        })
        .catch(error => {
          console.log(error)
        })
  }

  render() {
      const { movies } = this.state;
      return (
        <Row>
            {movies.map((movie, index) => (
                <Col key={index} sm={4} md={4} lg={3}>
                    <Card style={{ width: '18rem' }}>
                        <Card.Img variant="top" src={"http://image.tmdb.org/t/p/w300//"+movie.poster_path} />
                        <Card.Body>
                            <Card.Title>{movie.title}</Card.Title>
                            <Card.Text>
                                {movie.overview}
                            </Card.Text>
                        </Card.Body>
                    </Card>
                </Col>
                )
            )}
        </Row>
    )
  }
}
export default App;
    

就像 Bootstrap 一样,React Bootstrap 可让您将内容包装在行和列内。map函数会遍历您的电影状态并在卡片组件内传递选定的值。请注意key ={index} ,它会跟踪您map函数内的当前索引。检查您的浏览器,您将看到来自 TMDB API 的最受欢迎电影的多个卡片。

结论

您现在已经学会了如何使用 React.js 解析 JSON 数据。所获得的技能对于担任 React 开发人员和前端工程师等职位的开发人员最有用。为了进一步提高这项技能,您可以追求高级概念,例如通过动态导入进行代码拆分。当您希望提高代码性能时,这会派上用场。

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据