我在根据 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 bygetStaticProps
.
这意味着不要将 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/