javascript - 无法使用 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
解决方案
从文档:
如果您导出
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
推荐阅读
- javascript - Javascript最有效的方法来组合数组元素
- c# - 当对象经过特定旋转时播放声音
- javascript - 从 json 层次结构中的较低键嵌套或映射数据
- python - 用while循环取平均值
- react-native-gifted-chat - 反应原生天才聊天中的快速回复未显示
- go - 当没有这样的文件返回错误为 nil 时如何使用 os.Open
- sql - PostgreSQL 11 在行中选择前一个值以与 out sub select 进行比较
- javascript - 我如何让我的代码让用户提交一个品种的狗并返回特定品种的图片
- java - Java 从命令行参数读取文件并打印它
- types - rustc 奇怪地假设类型参数必须相同,即使它们是分开的?