我不断收到“无法读取未定义的属性(读取‘地图’)”错误

问题描述 投票:0回答:1

我在使用此代码时不断收到该错误。尽管尝试了一个我认为可以解决的关键问题,但问题还是不断出现。无论如何我可以修复它吗?

import React from "react";
import { useEffect, useState } from "react";

export default function Home() {
    const[dataResponse, setdataResponse] = useState([]);
    useEffect(() => {
        async function getPageData() {
            const apiUrlEndpoint = 'http://localhost:3000/api/games';
            const response = await fetch(apiUrlEndpoint);
            const res = await response.json();
            console.log(res.games);
            setdataResponse(res.games);
        }
        getPageData();
    }, []);
    
    return (
        <div className='bg-gray-100 min-h-screen'>
            
            {dataResponse.map((games) => {
                return (
                    <div key= {games.ProductID}>
                        <div>{games.ProductName}</div>
                    <div>
                        <img src={games.ProductImage} alt=""/>
                    </div>
                        <div>
                            {games.ProductDescription}
                        </div>
                    <div>
                        {games.DateWhenAdded}
                    </div>
                </div>   
             )
            })}
    </div>
);
}

这是我的API,也就是games.js:

import mysql from "mysql2/promise";

 export default async function handler(req, res) {
    const dbconnection = await mysql.createConnection({
        host: "localhost",
        database: "onlinestore",
        port: 3306,
        user: "root",
        password: "This is Private, I'm not showing password",
    });
    try {
        const query = "SELECT ProductID, ProductName, ProductDescription, ProductImage, ProductPrice, DateWhenAdded FROM games"
        const values = [];
        const [games] = await dbconnection.execute(query, values);
        dbconnection.end();
        for (const game of games) {
            game.ProductImage = `data:image/webp;base64,${games.ProductImage.toString('base64')}`;
            game.DateWhenAdded = formatDistanceToNowStrict(games.DateWhenAdded);
        }
        res.status(200).json(games);

    } catch (error) {
        res.status(500).json(error);
    }
 }

我尝试过的一件事是尝试?在 dataResponse 之后,看看我是否放入了一个“if”语句来确保它存在,如果它存在,就在它之后发布一些东西。

mysql next.js compiler-errors
1个回答
0
投票

我通过在某种意义上重新编写我的整个代码并添加一个不同的属性来解决这个问题,该属性允许我获取 mysql 日期并将其转换为 JS 日期格式并确保错误不再出现。

© www.soinside.com 2019 - 2024. All rights reserved.