React Native 点击生成随机数拼接API URL拉取数据的代码整合问题
React Native 随机数拼接API拉取数据整合方案
整合思路
- 统一使用当前生态更推荐的函数式组件写法,避免两种组件格式混用的适配问题
- 点击按钮后同步完成「生成随机数」+「拼接URL发起请求」的完整逻辑
- 修复原代码中对单条返回数据误用FlatList的语法问题
- 保留两段原始代码的所有核心功能
整合后完整代码
import React, { useState } from "react"; import { StyleSheet, View, Text, TouchableOpacity, Image, ActivityIndicator } from 'react-native'; import { Center, NativeBaseProvider, Button } from "native-base"; export default function RandomPhotoFetcher() { // 存储生成的随机数 const [randomId, setRandomId] = useState(0); // 存储接口返回的图片数据 const [photoData, setPhotoData] = useState(null); // 控制请求加载状态 const [loading, setLoading] = useState(false); const handleButtonPress = async () => { // 1. 生成1-5000区间的随机数 const newRandomNumber = Math.floor(Math.random() * 5000) + 1; setRandomId(newRandomNumber); // 2. 拼接URL发起接口请求 setLoading(true); try { const resp = await fetch(`https://jsonplaceholder.typicode.com/photos/${newRandomNumber}`); const result = await resp.json(); setPhotoData(result); } catch (err) { console.log('请求出错:', err); } finally { setLoading(false); } }; return ( <NativeBaseProvider> <Center flex={1} style={styles.MainContainer}> <Text style={{marginBottom: 10, fontSize: 20}}>当前生成的随机ID:{randomId}</Text> {/* 按钮/加载状态切换 */} {loading ? ( <ActivityIndicator size="large" color="#2563eb" /> ) : ( <Button title="生成随机数并拉取数据" onPress={handleButtonPress} /> )} {/* 渲染返回的图片信息 */} {photoData && ( <View style={styles.card} marginTop={20}> <Text style={styles.title}>图片标题:{photoData.title}</Text> <TouchableOpacity style={styles.list}> <Image source={{uri: photoData.thumbnailUrl}} style={{width: 150, height: 150, marginTop: 10}} /> </TouchableOpacity> </View> )} </Center> </NativeBaseProvider> ); } const styles = StyleSheet.create({ MainContainer: { flex: 1, justifyContent: 'center', alignItems: 'center', paddingHorizontal: 20 }, card: { width: '100%', padding: 15, backgroundColor: '#fff', borderRadius: 8, shadowColor: '#000', shadowOffset: {width: 0, height: 2}, shadowOpacity: 0.1, shadowRadius: 4, elevation: 3 }, title: { fontSize: 16, lineHeight: 22 }, list: { paddingVertical: 4, margin: 5, backgroundColor: '#fff', } });
关键调整说明
- 合并了两段代码的核心逻辑,不需要两次点击按钮即可完成完整流程
- 修复了原函数组件中错误使用
this调用renderItem的语法问题 - 适配了单条接口数据的渲染逻辑:原接口返回的是单个图片对象,不能直接传入FlatList的data属性(要求为数组),如果需要拉取列表数据可将接口地址替换为
https://jsonplaceholder.typicode.com/photos?albumId=${随机数} - 新增加载状态,避免用户重复发起请求
内容的提问来源于stack exchange,提问作者the_gujarati
相关产品推荐
相关产品推荐

