【问题标题】:getStaticProps not working from components foldergetStaticProps 在组件文件夹中不起作用
【发布时间】:2021-12-03 06:48:56
【问题描述】:

最近发了一个关于这个问题的问题:typeError: Cannot read property 'map' of undefined

我想使用带有getStaticProps 的组件并将其放入我的pages/index.js,但我不能使用我当前的代码。但是,如果我将此组件作为一个页面 (pages/component.js) 并像另一个页面一样打开,它就会正常工作。

组件Galery.js代码:

import styles from '../styles/galery.module.css'
import Image from 'next/image'
import Link from 'next/link'
import photo from '../public/01.png'

export const getStaticProps = async () => {

    const res = await fetch('https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card');
    const datas = await res.json();

    return {
        props: { datas }
    }
}

const Galery = ({ datas }) => {
    return (
        <div className={styles.galeryPage}>
            <h1 className={styles.title}>Projetos</h1>
            <div className={styles.galery}>
                <div className={styles.categoryWrapper}>
                    <h4 className={styles.subTitle}>Escritório</h4>
                    <div className={styles.lineWrapper}>
                        <a className={styles.leftArrow}>&#10094;</a>
                        <div className={styles.line}>
                            {datas.map((data) => (
                                <div className={styles.imageBox}>
                                    <Image src={photo} width={400} height={200} layout="responsive" lazy="true" placeholder="blur" />
                                    <div className={styles.linkContent}>
                                        <span className={styles.name} key={data.id}>{data.name}</span>
                                        <Link href=""><a className={styles.link}>Veja Mais!</a></Link>
                                    </div>
                                </div>
                            ))}
                        </div>
                        <a className={styles.rightArrow}>&#10095;</a>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Galery;

API 链接:https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card

这是我想要的结构: Desirable Structure

这是作为页面工作的结构: Structure that works

我应该怎么做才能按计划工作?

【问题讨论】:

  • getStaticProps 等数据获取方法只能从页面组件(pages 文件夹内的组件)中使用。我建议您在index.js 中获取页面级别的数据,并将其传递给您的Galery 组件。

标签: reactjs next.js fetch-api


【解决方案1】:

像 getStaticProps 这样的数据获取方法只能从页面组件(页面文件夹内的组件)中使用。我建议您在 index.js 中获取页面级别的数据,并将其传递给您的 Galery 组件。

juliomalves 是正确的!谢谢。

【讨论】:

    猜你喜欢
    • 2023-02-05
    • 2018-02-23
    • 2021-09-09
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 2017-10-04
    • 2019-02-09
    • 1970-01-01
    相关资源
    最近更新 更多