在React-Native中不使用List组件如何展示JSON数据?
正确实现方案:用Fetch获取JSON并手动渲染列表项
我来帮你梳理下原代码里的问题,再给出完整的修正版实现:
原代码的核心问题
- 接口返回JSON格式不合法:你提供的接口返回是多个独立JSON对象直接拼接(
{"id":"1"...}{"id":"2"...}),这不是标准JSON数组,直接解析会报错,需要先处理成合法格式 - 状态管理错误:你把接口返回的
data存在了全局变量,没有存入组件state,导致组件无法响应数据变化触发重新渲染 - 语法与逻辑错误:
foreach拼写错误(应为forEach),数组添加元素要用push而非put;setState里的字段名和state定义的isLoading不一致;renderItems返回的React元素数组不能用<Text>包裹渲染
修正后的完整代码
import React from 'react'; import { View, Text, ActivityIndicator, StyleSheet } from 'react-native'; import { Card } from 'react-native-paper'; // 若未使用该组件,可替换为普通View export default class HomeScreen extends React.PureComponent { constructor(props) { super(props); this.state = { isLoading: true, data: [], // 新增状态存储接口返回的数据 }; } componentDidMount() { fetch(`http://www.example.com/React/data.php`, { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, // 若接口不需要POST参数可删除body;如需传参,添加对应内容 // body: JSON.stringify({ param: 'value' }) }) .then((response) => response.text()) // 先获取文本,处理非标准JSON .then((responseText) => { // 将非标准JSON转换为合法数组格式 const fixedJson = `[${responseText.replace(/}{/g, '},{')}]`; const responseJson = JSON.parse(fixedJson); this.setState({ data: responseJson, isLoading: false, // 与state定义的字段名保持一致 }); }) .catch((error) => { console.warn('请求出错:', error); this.setState({ isLoading: false }); // 出错后停止加载状态 }); } renderItems() { // 遍历state中的数据,生成对应的React元素 return this.state.data.map((dataItem) => ( <Card key={dataItem.id} style={styles.cardItem}> <View style={styles.cardContent}> <Text>ID: {dataItem.id}</Text> <Text>图片名称: {dataItem.imagename}</Text> </View> </Card> )); } render() { if (this.state.isLoading) { return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <ActivityIndicator size="large" color="#fff" /> </View> ); } return( <View style={styles.MainContainer}> {/* 直接渲染元素数组,无需额外包裹Text */} {this.renderItems()} </View> ); } } const styles = StyleSheet.create({ MainContainer: { flex:1, padding: 10, backgroundColor: '#333', }, cardItem: { marginBottom: 10, padding: 15, }, cardContent: { gap: 5, }, });
关键修改说明
- 修复JSON格式问题:因为后端返回的不是合法数组,我们先获取文本响应,通过字符串处理将其转换为合法的JSON数组(添加首尾
[],把}{替换为},{),再解析为JS对象 - 规范状态管理:在state中新增
data字段存储接口数据,确保组件能通过状态变化触发重新渲染 - 修正语法与渲染逻辑:
- 用更简洁的
map替代forEach直接生成元素数组 - 渲染时直接输出
renderItems()返回的元素数组,无需<Text>包裹 - 统一状态字段名
isLoading,避免状态更新不生效
- 用更简洁的
- 完善错误处理:请求出错时更新
isLoading状态,避免一直显示加载指示器
内容的提问来源于stack exchange,提问作者Laney Williams
相关产品推荐
相关产品推荐

