简体   繁体   中英

getStaticProps Problems (NEXTJS)

Recently I made a question about this problem: typeError: Cannot read property 'map' of undefined.

I want to use a component with getStaticProps and put it in my pages/index.js, but I can't with my current code. BUT, if I put this component as a page (pages/component.js) and open like a different page it just work as it should do.

The component Galery.js code:

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 link: https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card

And this is the structure that I would like to have: Desirable Structure

And this is the structure that works as a page: Structure that works

What I should do to work as I planned?

Data fetching methods like getStaticProps can only be used from page components (components inside pages folder). I'd suggest you fetch the data at the page level in index.js, and pass it down to your Galery component.

juliomalves is correct! Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM