javascript - 无法正确使用 Next.js 进行获取

标签 javascript reactjs async-await next.js

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

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

最佳答案

来自文档:

If you export an async function called getStaticProps from a page, Next.js will pre-render this page at build time using the props returned by 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

关于javascript - 无法正确使用 Next.js 进行获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60689204/

相关文章:

javascript - 从异步函数设置全局变量

javascript - 功能组件 : Write functions inside or outside the component?

reactjs - React-router-dom History.goBack() 在 Firefox 和 Safari 上不起作用

javascript - 异步/等待链中的一个 promise 失败的优雅回退?

c# - EF中这两个异步调用有什么区别?

javascript - 使用 D3PLUS 在 TreeMap 中使用 json 递归的问题

javascript - 覆盖 JavaScript 函数中的属性

javascript - jS居中功能不适用于页面加载中的一个元素,只需调整大小

javascript - 我如何通过在 reactJS 的 Material 表中创建新行来访问取消处理程序?

c# - FindAsync 很慢,但是延迟加载很快