You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Expo中如何将Container的数组数据渲染至Component?

问题解决:数组数据渲染时返回undefined的修复

问题根源

你在Container中定义的ordersdetails是数组类型,但在Component里直接尝试访问ordersdetails.nOrder这类对象属性——数组本身没有这些属性,所以会返回undefined。之前用FlatList时是遍历数组取每一项,因此正常;现在直接渲染需要明确获取数组中的具体元素。

修复方案(两种可选)

方案1:在Container中传递数组的单个元素

修改Container代码,直接把数组的第一个元素传给Component:

import React from 'react'
import OrdersDetailsComponent from '../components/OrdersDetailsComponent';

const OrdersDetails = (props) => {
    const ordersdetails = [{
        id: "1",
        nOrder: "Pedido N566",
        street: " C/ del Áncora, 6",
        time: 1630,
        tab: 'Recogidas',
        map: require('../../elements/assets/MapExample.png'),
        contact: [{
            name: "Celia Sánchez",
            phone: '+34 654 654 654',
        }],
        Asignado: "Lourdes Martín"
    }]

    // 传递数组的第一个元素
    return (
        <OrdersDetailsComponent
            ordersdetails={ordersdetails[0]}
            {...props} />
    )
}
export default OrdersDetails;

方案2:在Component中访问数组的具体元素

如果需要保留传递数组的逻辑,在Component里取数组第一项,同时用可选链操作符?.避免数组为空时报错:

const OrdersDetailsComponent = ({ ordersdetails, navigation }) => {
    // 取数组第一个元素,可选链防止数组为空
    const order = ordersdetails[0];

    return (
        <Layout style={styles.wrapper}>
            <SimpleHeader
                style={styles.head}
                title={<Text style={styles.title}>{order?.nOrder}</Text>}
                onBackPress={() => navigation.goBack()}
            />

            <View style={styles.section}>
                <Text>Detalles del pedido</Text>
            </View>

            <View>
                <View>
                    <Text style={styles.text}>{order?.street}</Text>
                    <Text style={styles.text}>{order?.time}</Text>
                </View>
                <View>
                    <Image source={order?.map} style={styles.image}></Image>
                </View>
            </View>

            <View style={styles.section}>
                <Text>Contacto</Text>
            </View>
            <View style={styles.sectionData}>
                <Text>{order?.contact[0]?.name}</Text>
                <Text>{order?.contact[0]?.phone}</Text>
            </View>

            <View style={styles.section}>
                <Text>Asignado</Text>
            </View>
            <View style={styles.sectionData}>
                <Text>Empleado({order?.Asignado})</Text>
            </View>
        </Layout>
    );
};

额外优化点

  • 注意Asignado的大小写,Container里定义的是大写开头,Component里要对应一致
  • 对于contact这种嵌套数组,同样需要取具体元素(比如contact[0].name)
  • 添加可选链?.可以避免数据为空时出现崩溃

内容的提问来源于stack exchange,提问作者Alfonso.b

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 20:19:01