【问题标题】:Can't print data from database in react. Getting TypeError: Cannot read properties of undefined (reading 'productname')无法在反应中打印数据库中的数据。获取 TypeError:无法读取未定义的属性(读取“产品名称”)
【发布时间】:2022-01-01 15:03:32
【问题描述】:
router.get("/product",async(req,res) => {
        try {
            const data = await Product.find({});
            console.log(data);
            res.send(data);
        } catch (error) {
            console.log(error);
        }
    });

上面的代码成功地从数据库中获取数据并在控制台中打印出来。 现在在前端

function Product() {
    useEffect (() => {
        fetchItems();
    },[]);

    const [items, setItems] = useState([]);

    const fetchItems = async() => {
        const data = await fetch('/product',{
            method: "GET",
            headers: {
                Accept: "application/json",
                "Content-Type": "application/json"
            },
            credentials: "include"
        });
        const items = await data.json();
        setItems(items);
    };

    return (
        <div>
            <h1>Product Page</h1>
            {
                items.map(item => {
                    <p>{item.product.productname} {item.product.producttype} {item.product.productprice}</p>
                })
            }

        </div>
    )
}

由于出现类型错误,我无法打印任何项目。集合的名称是 products。

【问题讨论】:

  • 这个错误是不言自明的。 item.product 未定义,因此尝试执行 item.product.productname 会产生该错误。你打印items看数据是不是你认为的形状?
  • 我收到此错误错误:对象作为 React 子项无效(找到:带有键 {_id、productname、productprice、producttype} 的对象)。如果您打算渲染一组子项,请改用数组。
  • @RitikSingh 能否请您出示const items = await data.json(); console.log('&lt;&lt;== items ==&gt;&gt; ', items); setItems(items); 的回复谢谢!
  • @JIGNESHPATEL 错误:对象作为 React 子项无效(发现:具有键 {_id、productname、productprice、producttype} 的对象)。如果您打算渲染一组子项,请改用数组。
  • @RitikSingh try npm i core-js 将此行放入您的index.js 文件的第一行。 import core-js。并将地图替换为items &amp;&amp; items.map(item =&gt; { return ( &lt;p&gt;{item.product.productname} {item.product.producttype} {item.product.productprice}&lt;/p&gt;) }) 希望它对你有用。

标签: node.js reactjs mongodb frontend


【解决方案1】:

这是因为您的项目首先呈现并且您的状态在返回后设置,这是反应中的常见问题 做吧:

 return (
    <div>
        <h1>Product Page</h1>
        {(items?.length > 0) &&
            items?.map(item => {
                <p>{item?.product?.productname} {item?.product?.producttype} {item?.product?.productprice}</p>
            })
        }
    </div>
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2021-11-13
    • 2022-01-14
    • 2022-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多