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

如何将对象数组传递给React Native组件并渲染数据

问题解决:React Native组件层级间数据传递失败

问题概述

我有一组产品对象数组,尝试通过ProductContainer -> FlatList -> ProductList -> ProductCard的层级传递数据,能在ProductList中打印出对象,但无法在ProductCard中渲染或打印item.price。

错误原因及修正方案

1. ProductList.js 中的错误

  • 变量名不匹配:传递的props属性是item,但解构时写成了items
  • 未返回JSX:组件没有用return输出渲染内容
  • 传递参数错误:给ProductCard传值时用了未定义的item变量

修正后的ProductList.js:

import ProductCard from "./ProductCard";
import { Dimensions, TouchableOpacity, View } from "react-native";

var { width } = Dimensions.get("window");

const ProductList = (props) => {
  // 修正:接收正确的props属性名
  const { item } = props;
  console.log(item.price);

  // 修正:添加return返回渲染元素
  return (
    <TouchableOpacity style={{ width: "50%" }}>
      <View style={{ width: width / 2, backgroundColor: "gainsboro" }}>
        {/* 修正:传递正确的item变量 */}
        <ProductCard {...item} />
      </View>
    </TouchableOpacity>
  );
};

export default ProductList;

2. ProductCard.js 中的错误

  • props解构错误:错误地将参数写成({ props }),实际接收的是展开后的产品属性

修正后的ProductCard.js(两种可选写法):

写法1:直接解构需要的属性

import { View, Text } from "react-native";

const ProductCard = ({ price }) => {
  console.log(price);
  return (
    <View>
      <Text>{price}</Text>
    </View>
  );
};

export default ProductCard;

写法2:接收完整props对象

import { View, Text } from "react-native";

const ProductCard = (props) => {
  console.log(props.price);
  return (
    <View>
      <Text>{props.price}</Text>
    </View>
  );
};

export default ProductCard;

3. ProductContainer.js 中的潜在问题

代码中导入的是data变量,但FlatList用的是products,需确保两者对应:

const data = require("../../assets/data/products.json");
const products = data; // 若JSON结构是数组直接赋值,若是嵌套结构则用data.products

验证效果

修改完成后,ProductCard将正确渲染产品价格,ProductList中的console.log(item.price)也会正常输出对应数值。

内容的提问来源于stack exchange,提问作者Amar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 05:40:25