首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对产品的映射和获取“对象无效为React子”错误

对产品的映射和获取“对象无效为React子”错误
EN

Stack Overflow用户
提问于 2022-07-07 04:31:18
回答 2查看 55关注 0票数 2

我的React.js代码收到了以下错误:

对象作为React子对象无效(找到:键{rate,count}的对象)。如果您打算呈现一个子集合,请使用数组代替。

代码语言:javascript
复制
    import logo from './logo.png';
    import './App.css';
    import React, { useState, useEffect } from "react";
    import axios from "axios";

    const idealoBackendUrl = "https://fakestoreapi.com/products"


    function App() {


    const render_products = (Products) => {
        console.log('.............................')
        console.log(Products)
        console.log('lllllllllllllllllllllllllllll')
        console.log(Products[0])
        console.log(typeof(Products))
        const result = Object.values(Products[0]);

        console.log(result);
        console.log('result typeee')
        console.log(typeof(result));
        console.log('................................')
        console.log(itemData)
        console.log(typeof(itemData))
       
        return <div className='category-section fixed'>
            <h2 className="text-3xl font-extrabold tracking-tight text-gray-600 category-title">Products</h2>

            <div className="m-6 p-3 mt-10 ml-0 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-6 xl:gap-x-10" style={{ maxHeight: '800px', overflowY: 'scroll' }}>
                {/* Loop Products */}
                {Products[0].map(product => (
                    <div className="group relative shadow-lg" >
                        <div className=" min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-60 lg:aspect-none">
                            <img
                                alt="Product Image"
                                src={logo}
                                className="w-full h-full object-center object-cover lg:w-full lg:h-full"
                            />
                        </div>
                        <div className="flex justify-between p-3">
                            <div>
                                <h3 className="text-sm text-gray-700">
                                    <a href={product.href}>
                                        <span aria-hidden="true" className="absolute inset-0" />
                                        <span style={{ fontSize: '16px', fontWeight: '600' }}>{product.item_name}</span>
                                    </a>
                                    <p>Tag -</p>
                                </h3>
                                <p className="mt-1 text-sm text-gray-500">Rating: {product.rating}</p>
                            </div>
                            <p className="text-sm font-medium text-green-600">${product.current_price}</p>
                        </div>
                    </div>
                ))}
            </div>
        </div>
    }

    const [itemData, setItemData] = useState(null);
    const [error, setError] = React.useState(null);

    useEffect(() => {
        getItemDataWithAxios().then(r => console.log(r));
    }, []);

    const getItemDataWithAxios = async () => {
        const response = await axios.get(idealoBackendUrl);
        console.log('print response data')
        console.log(response.data);
        setItemData(response.data);
    };

    if (error) return `Error: ${error.message}`;
    if (!itemData) return <center style={{ marginTop: '200px' }}> <img src="https://icons8.com/preloaders/preloaders/1474/Walk.gif" style={{ width: '70px' }} /> </center>;
  

    return (
          
              <div className="flex fixed flex-row">
                  <div className="h-screen  bg-slate-800 p-3 xl:basis-1/5" style={{ minWidth: '65%' }}>
                      <img className="w-full" src={logo} alt="Sunset in the mountains" />
                      <div className="px-6 py-4">
                          <h1 className="text-3xl mb-2 font-bold text-white"> Idealo product catalog </h1>
                          <p className="text-gray-700 text-white">
                              by - <b style={{ color: 'orange' }}>Sithija</b>
                          </p>
                      </div>
                  </div>
                  <div className="ml-5  p-10 xl:basis-4/5">
                      {render_products([itemData])}
                  </div>
              </div>
          // </>
       
      );
    }
    
    export default App;

我有上面的代码,我一直得到上面提到的错误,但我找不到根本原因。

我注意到在调用render_products = (Products)时,Products是一个单独的对象数组,其中应该是20个对象数组。我试过的产品也没有成功。

有人能看到这里出了什么问题吗?

EN

回答 2

Stack Overflow用户

发布于 2022-07-07 04:47:26

问题在问题标题中,您正试图在product.rating方法中显示{ render_products }。它不是一个数字,而是一个{rate,count}作为键的对象。请参考以下代码。

代码语言:javascript
复制
import React, { useState, useEffect } from "react";
import axios from "axios";

const idealoBackendUrl = "https://fakestoreapi.com/products"


function App() {


const render_products = (Products) => {
   
    return <div className='category-section fixed'>
        <h2 className="text-3xl font-extrabold tracking-tight text-gray-600 category-title">Products</h2>

        <div className="m-6 p-3 mt-10 ml-0 grid grid-cols-1 gap-y-10 gap-x-6 sm:grid-cols-2 lg:grid-cols-6 xl:gap-x-10" style={{ maxHeight: '800px', overflowY: 'scroll' }}>
            {/* Loop Products */}
            {Products.map(product => (
                <div className="group relative shadow-lg" >
                    <div className=" min-h-80 bg-gray-200 aspect-w-1 aspect-h-1 rounded-md overflow-hidden group-hover:opacity-75 lg:h-60 lg:aspect-none">
                        <img
                            alt="Product Image"
                            src=""
                            className="w-full h-full object-center object-cover lg:w-full lg:h-full"
                        />
                    </div>
                    <div className="flex justify-between p-3">
                        <div>
                            <h3 className="text-sm text-gray-700">
                                <a href={product.href}>
                                    <span aria-hidden="true" className="absolute inset-0" />
                                    <span style={{ fontSize: '16px', fontWeight: '600' }}>{product.item_name}</span>
                                </a>
                                <p>Tag -</p>
                            </h3>
                            {/* Here was the issue */}
                            <p className="mt-1 text-sm text-gray-500">Rating: {product.rating.rate}</p>
                        </div>
                        <p className="text-sm font-medium text-green-600">${product.current_price}</p>
                    </div>
                </div>
            ))}
        </div>
    </div>
}

const [itemData, setItemData] = useState(null);
const [error, setError] = React.useState(null);

useEffect(() => {
    getItemDataWithAxios().then(r => console.log(r));
}, []);

const getItemDataWithAxios = async () => {
    const response = await axios.get(idealoBackendUrl);
    console.log('print response data')
    console.log(response.data);
    setItemData(response.data);
};

if (error) return `Error: ${error.message}`;
if (!itemData) return <center style={{ marginTop: '200px' }}> <img src="https://icons8.com/preloaders/preloaders/1474/Walk.gif" style={{ width: '70px' }} /> </center>;


return (
      
          <div className="flex fixed flex-row">
              <div className="h-screen  bg-slate-800 p-3 xl:basis-1/5" style={{ minWidth: '65%' }}>
                  <img className="w-full" src="" alt="Sunset in the mountains" />
                  <div className="px-6 py-4">
                      <h1 className="text-3xl mb-2 font-bold text-white"> Idealo product catalog </h1>
                      <p className="text-gray-700 text-white">
                          by - <b style={{ color: 'orange' }}>Sithija</b>
                      </p>
                  </div>
              </div>
              <div className="ml-5  p-10 xl:basis-4/5">
                  {render_products(itemData)}
              </div>
          </div>
      // </>
   
  );
}

export default App;

请随意编辑代码,以包括您的徽标组件和其他图标,我删除了他们,因为我没有这些项目的副本。

票数 0
EN

Stack Overflow用户

发布于 2022-07-07 04:49:39

试试这个:

代码语言:javascript
复制
...
{Products.map(product => (
...
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/72892306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档