React Native渲染MongoDB Decimal数据报错及日期格式化求助
解决React Native FlatList渲染交易数据的两个问题
一、处理MongoDB Decimal类型渲染错误
接口返回的amount、credit、debit字段是MongoDB Decimal类型,以{$numberDecimal: "数值"}的对象形式存在,直接作为React子元素渲染会抛出Objects are not valid as a React child错误,有两种解决方式:
方式1:渲染时直接提取数值
在FlatList的renderItem中,直接访问对象的$numberDecimal属性:
<Text>{item.amount.$numberDecimal}</Text>
方式2:获取数据后统一预处理
在getTransactionsList中,对返回的交易数据进行遍历转换,把Decimal对象转为字符串,后续渲染直接使用转换后的字段:
getTransactionsList = async () => { let token = await AsyncStorage.getItem('token'); let email = await AsyncStorage.getItem('email'); fetch('https://webserver-migospay.onrender.com/api/user-data/get-transactionby-email/' + email, { method: 'GET', headers: { 'Content-type': 'application/json', 'Authorization': `Bearer ${token}`, }, }) .then(response => response.json()) .then(responseJson => { // 预处理Decimal字段 const processedData = responseJson.map(item => ({ ...item, amount: item.amount.$numberDecimal, credit: item.credit.$numberDecimal, debit: item.debit.$numberDecimal })); setTransaction_details(processedData); setLoading(false); }); };
二、ISO日期格式化为YYYY-MM-DD
接口返回的created_at是ISO格式字符串(如2022-12-20T09:26:06.030Z),需要格式化为2022-12-20的形式,可通过以下方式实现:
方法1:字符串分割(简单直接)
直接按T分割字符串,取前半部分:
<Text>{item.created_at.split('T')[0]}</Text>
方法2:工具函数格式化(更严谨)
定义一个日期格式化函数,处理可能的异常情况:
const formatDate = (isoString) => { if (!isoString) return ''; const date = new Date(isoString); const year = date.getFullYear(); const month = String(date.getMonth() + 1).padStart(2, '0'); const day = String(date.getDate()).padStart(2, '0'); return `${year}-${month}-${day}`; };
在renderItem中使用:
<Text>{formatDate(item.created_at)}</Text>
修改后的FlatList关键代码
<FlatList data={transaction_details} ItemSeparatorComponent={this.FlatListItemSeparator} renderItem={({ item }) => { return ( <View> <View style={{ flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}> <Text>{item.narration}</Text> {/* 使用预处理后的amount或直接取$numberDecimal */} <Text>{item.amount}</Text> </View> {/* 格式化日期 */} <Text>{formatDate(item.created_at)}</Text> </View> ) }} keyExtractor={(item) => item._id.toString()} />
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

