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

如何在React Native中通过ID从REST API获取并展示数据

按ID获取并展示单条电影数据的React Native实现

现有代码

import React, { Component } from 'react';
import { ActivityIndicator, FlatList, Text, View } from 'react-native';

export default class App extends Component {
constructor(props) {
super(props);

this.state = {
  data: [],
  isLoading: true
};
}

async getMovies() {
try {
  const response = await fetch('https://reactnative.dev/movies.json');
  const json = await response.json();
  this.setState({ data: json.movies });
} catch (error) {
  console.log(error);
} finally {
  this.setState({ isLoading: false });
}
}

componentDidMount() {
this.getMovies();
}

render() {
const { data, isLoading } = this.state;

return (
  <View style={{ flex: 1, padding: 24 }}>
    {isLoading ? <ActivityIndicator/> : (
      <FlatList
        data={data}
        keyExtractor={({ id }, index) => id}
        renderItem={({ item }) => (
          <Text>{item.title}, {item.releaseYear}</Text>
        )}
      />
    )}
  </View>
  );
 }
};

对应API结构

{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "id": "1", "title": "Star Wars", "releaseYear": "1977" },
{ "id": "2", "title": "Back to the Future", "releaseYear": "1985" },
{ "id": "3", "title": "The Matrix", "releaseYear": "1999" },
{ "id": "4", "title": "Inception", "releaseYear": "2010" },
{ "id": "5", "title": "Interstellar", "releaseYear": "2014" }
]
}

修改需求

需要修改上述代码,实现通过指定ID(例如ID=1)获取对应电影数据,并在页面中展示该电影的信息,核心要解决按ID筛选数据和单条数据渲染两个问题。

实现方案与修改后代码

由于当前提供的API仅返回全部电影列表,没有单个ID的查询端点,因此我们先获取完整列表,再通过ID筛选目标条目。具体修改如下:

import React, { Component } from 'react';
import { ActivityIndicator, Text, View } from 'react-native';

export default class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      // 改为存储单条电影对象,初始为null
      movie: null,
      isLoading: true
    };
  }

  // 新增参数movieId,用于指定要查询的电影ID
  async getMovieById(movieId) {
    try {
      const response = await fetch('https://reactnative.dev/movies.json');
      const json = await response.json();
      // 从电影列表中筛选出ID匹配的条目
      const targetMovie = json.movies.find(movie => movie.id === movieId);
      this.setState({ movie: targetMovie });
    } catch (error) {
      console.log(error);
    } finally {
      this.setState({ isLoading: false });
    }
  }

  componentDidMount() {
    // 传入目标ID(例如1)发起请求
    this.getMovieById('1');
  }

  render() {
    const { movie, isLoading } = this.state;

    return (
      <View style={{ flex: 1, padding: 24, justifyContent: 'center' }}>
        {isLoading ? (
          <ActivityIndicator size="large" />
        ) : movie ? (
          // 渲染单条电影的详细信息
          <View>
            <Text style={{ fontSize: 20, fontWeight: 'bold', marginBottom: 8 }}>{movie.title}</Text>
            <Text style={{ fontSize: 16 }}>上映年份:{movie.releaseYear}</Text>
          </View>
        ) : (
          <Text style={{ fontSize: 16 }}>未找到对应ID的电影</Text>
        )}
      </View>
    );
  }
};

关键修改点说明

  • 状态结构调整:将原data数组改为movie对象,用于存储单条筛选后的电影数据
  • 请求函数优化:新增getMovieById函数,接收movieId参数,获取全量数据后用find方法筛选匹配ID的条目
  • 渲染逻辑变更:移除FlatList,直接渲染单条电影的标题和上映年份,同时处理未找到对应电影的情况
  • 加载状态优化:调整ActivityIndicator的尺寸,并优化布局居中显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:10:34