首页 > 解决方案 > 如何渲染对象内的对象数组反应本机?

问题描述

这是我的 JSON:

{
"products": [
           {
               "_id": "5fc9027dd3b8f63398ae8132",
               "name": "Oriz 500g",
               "quantity": 1
           }
       ],
       "status": "CANCELLED",
       "total": 0,
}

我需要从产品中呈现名称和数量。我正在渲染这样,但它不起作用

<Text style={styles.listProduct}>{data.products.name}</Text>

注:数据来自

const [data, setData] = useState([]);
const response = await axiosApiInstance.get(
      `/orders/get-order-details/5fce356c0fbc3605bffe2060`
    );
    setData(response.data);

标签: javascriptreactjsperformancereact-nativefirebase-realtime-database

解决方案


您需要在数组中循环并提取所需的数组项,请遵循此

<View>
    {data.length > 0 && data.products.map((element, index) => {
      return (
        <View>
          <Text style={styles.listProduct}>Name: {element.name}</Text>
          <Text style={styles.listProduct}>Quantity: {element.quantity}</Text>
        </View>
      );
    })}
  </View>

根据您的要求修改


推荐阅读