React Native页面初始化时出现data[0].given_amount未定义渲染错误
React Native组件初始渲染API数据报错解决
问题原因
组件首次渲染时,data是初始化的空数组[],此时data[0]为undefined,直接访问data[0].given_amount会触发undefined is not an object(evaluating 'data[0].given_amount')错误。等API请求完成并更新data状态后,数组有了数据,页面就能正常渲染。
解决方案
方案1:使用可选链操作符(推荐)
在访问嵌套属性时添加?.,当左侧值为undefined或null时,表达式会短路返回undefined,避免报错:
import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import { styles } from './style'; import Colors from '../../constants/colors'; import { useTranslation } from 'react-i18next'; import * as api from '../../core/api'; import BackHeader from '../../components/backheader/backheader'; const Ethstaking = props => { const { t } = useTranslation(); const [data, setData] = useState([]); const stakingInfo = async () => { let res = await api.stakingInfo(); console.log("ethstake------", res.data.data) setData(res.data.data); } useEffect(() => { stakingInfo(); }, []); return ( <View style={{ flex: 1, backgroundColor: Colors.white }}> <BackHeader name={t('ethstake')} navigation={props.navigation} /> <View style={styles.Container}> <View style={styles.card}> <Text style={styles.row}>{t('givenamt')}: {data[0]?.given_amount}</Text> <Text style={styles.row}>{t('lastincome')}: {data[0]?.yesterday_income}</Text> <Text style={styles.row}>{t('totalincome')}: {data[0]?.total_income}</Text> <Text style={styles.row}>{t('totaleth')}: {data[0]?.total_eth}</Text> </View> </View> </View> ); }; export default Ethstaking;
方案2:条件渲染(显示加载状态)
先判断data是否有数据,没有数据时显示加载提示,有数据再渲染内容:
import React, { useEffect, useState } from 'react'; import { View, Text } from 'react-native'; import { styles } from './style'; import Colors from '../../constants/colors'; import { useTranslation } from 'react-i18next'; import * as api from '../../core/api'; import BackHeader from '../../components/backheader/backheader'; const Ethstaking = props => { const { t } = useTranslation(); const [data, setData] = useState([]); const stakingInfo = async () => { let res = await api.stakingInfo(); console.log("ethstake------", res.data.data) setData(res.data.data); } useEffect(() => { stakingInfo(); }, []); if (data.length === 0) { return ( <View style={{ flex: 1, backgroundColor: Colors.white, justifyContent: 'center', alignItems: 'center' }}> <Text>{t('loading')}</Text> </View> ); } return ( <View style={{ flex: 1, backgroundColor: Colors.white }}> <BackHeader name={t('ethstake')} navigation={props.navigation} /> <View style={styles.Container}> <View style={styles.card}> <Text style={styles.row}>{t('givenamt')}: {data[0].given_amount}</Text> <Text style={styles.row}>{t('lastincome')}: {data[0].yesterday_income}</Text> <Text style={styles.row}>{t('totalincome')}: {data[0].total_income}</Text> <Text style={styles.row}>{t('totaleth')}: {data[0].total_eth}</Text> </View> </View> </View> ); }; export default Ethstaking;
方案3:初始化状态为包含空对象的数组
把初始data设为[{}],这样首次渲染时data[0]是一个空对象,访问属性不会报错,只会显示空值,等API数据回来后再覆盖:
const [data, setData] = useState([{}]);
内容的提问来源于stack exchange,提问作者milica98
相关产品推荐
相关产品推荐

