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

React渲染数据库数据报错:TypeError 读取productname属性为undefined

报错原因

  • 后端Product.find({})查询返回的数组中,每个元素本身就是完整的产品对象,不存在嵌套的product字段,前端代码多写了一层.product访问,导致读取undefined的productname属性触发报错
  • map回调函数使用了带大括号的写法但没有写return,就算字段匹配正确也渲染不出内容,同时React列表渲染缺少key属性会抛出警告

解决步骤

  1. 去掉字段访问时多余的.product层级,直接访问item.productname这类属性
  2. 修正map回调的返回写法,同时给列表项加唯一key(推荐使用数据库返回的_id字段)
  3. 可选优化:增加加载状态和异常捕获,避免异步请求未完成时的访问异常

修正后前端代码

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

    const [items, setItems] = useState([]);
    const [loading, setLoading] = useState(true);

    const fetchItems = async() => {
        try {
            const data = await fetch('/product',{
                method: "GET",
                headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json"
                },
                credentials: "include"
            });
            const items = await data.json();
            setItems(items);
        } catch (err) {
            console.error('请求异常:', err);
        } finally {
            setLoading(false);
        }
    };

    if (loading) return <div>加载中...</div>

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:24:02