I keep getting "Cannot read properties of undefined (reading 'map')" Error

huangapple go评论65阅读模式
英文:

I keep getting "Cannot read properties of undefined (reading 'map')" Error

问题

在使用这段代码时,我一直遇到这个错误。尽管尝试了一项我认为可以解决它的关键方法,但问题仍然不断出现。有没有办法我可以修复它?

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: "这是私人信息,我不会显示密码",
    });
    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"语句来确保它存在,如果存在的话,就在它后面发布一些内容。

英文:

I keep getting that error while using this code. The problem keeps popping up despite having trying a key thing I thought would fix it. Is there anyway I can fix it?

import React from &quot;react&quot;;
import { useEffect, useState } from &quot;react&quot;;

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

This is my API, which is games.js:

import mysql from &quot;mysql2/promise&quot;;

 export default async function handler(req, res) {
    const dbconnection = await mysql.createConnection({
        host: &quot;localhost&quot;,
        database: &quot;onlinestore&quot;,
        port: 3306,
        user: &quot;root&quot;,
        password: &quot;This is Private, I&#39;m not showing password&quot;,
    });
    try {
        const query = &quot;SELECT ProductID, ProductName, ProductDescription, ProductImage, ProductPrice, DateWhenAdded FROM games&quot;
        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(&#39;base64&#39;)}`;
            game.DateWhenAdded = formatDistanceToNowStrict(games.DateWhenAdded);
        }
        res.status(200).json(games);

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

One thing I did try was trying the ? after the dataResponse, and seeing if I put in an "if" statement to make sure it exists, and to post something after it if it does.

答案1

得分: 0

我通过重新调整我的整个代码并添加一个不同的属性来解决了这个问题,这使我能够将MySQL日期转换为JS日期格式,并确保不再出现错误。

英文:

I figured this out by reworking my whole code in a sense and adding in a different property that allowed me to take the mysql date and turn it into JS date format and making sure that error no longer appears.

huangapple
  • 本文由 发表于 2023年3月7日 06:11:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75656313.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定