如何在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
相关产品推荐
相关产品推荐

