首页 > 解决方案 > 无法使用 Next.js 正确进行提取

问题描述

根据 Next.js 网站上提供的文档,我无法进行提取。我试图安慰我无法出现的道具。我没有使用 Next 的经验,试图将其镜像到 React,但不幸的是它不起作用。如何使用 getStaticProps 进行提取?我有一个将 getInitialProps 用于旧版本 Next.js 的教程,但我正在尝试遵循他们的新文档。这是我到目前为止的入门代码:

import React, { Component } from 'react';
// import fetch from 'node-fetch'

class Index extends Component {
    state = {}

    getStaticProps = async () => {
        // Call an external API endpoint to get posts.
        console.log('fetching data')
        const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
        const posts = await res.json()


        return {
            props: {
                posts,
            },
        }

    }
    render() {
        console.log(this.props)
        return (
            <div>
                <h1>Our Index Page!!</h1>
            </div>
        );
    }
}


export default Index

标签: javascriptreactjsasync-awaitnext.js

解决方案


从文档:

如果您导出getStaticProps从页面调用的异步函数,Next.js 将在构建时使用getStaticProps.

这意味着不要让你getStaticProps在组件内部,而是将其导出为:

import React, { Component } from 'react';
// import fetch from 'node-fetch'

class Index extends Component {
    state = {}

    render() {
        console.log(this.props)
        return (
            <div>
                <h1>Our Index Page!!</h1>
            </div>
        );
    }
}

export const getStaticProps = async () => {
    // Call an external API endpoint to get posts.
    console.log('fetching data')
    const res = await fetch('https://jsonplaceholder.typicode.com/todos/1')
    const posts = await res.json()
    return {
        props: {
            posts,
        },
    }
}

export default Index

推荐阅读