开发者问题收集

Next.js 中的数据提取

2022-08-07
109

假设我想从一个网站获取数据,该网站的链接是 http://cookiestats.net/cookies ,该链接上的数据如下:

{"cookie-stats": {"eating": 1, "eaten": "6"}, "people-eating": {"current": 3, "total": "6"}>

我做错了什么?

export const getStaticProps = async () => {
    const res = await fetch('http://cookiestats.net/cookies');
    const data = await res.json();
    
    return{
        props: {cookies: data}
    }
}

const Cookies = ({ cookies }) => {
    return (
        <div>
            <h1>Cookie Data</h1>
            {Object.keys(cookies).map(cookies => (
                <div key = {cookies.cookie-stats}>
                    <a>
                        <h3>{cookies.eating}</h3>
                    </a>
                    </div>
            ))}
        </div>
    );
}

export default Cookies;
1个回答

您正在尝试映射一个不可能的对象。相反,您可以尝试使用方法 Object.keys :

 Object.keys(cookies).map(cookiesKey => (
     <div key = {cookies[cookiesKey]}>
         <a>
            <h3>{cookies[cookiesKey]}</h3>
         </a>
     </div>
 ))}
juakog
2022-08-07