我正在阅读 Nextjs 获取文档的数据部分,我想到了一个问题。
Nextjs 可以使用 getStaticProps、getStaticPaths、getInitialProps 和 getServersideProps 获取数据,对吗?
但正如我引用的那样,有些发生在构建时:
getStaticProps(静态生成):在构建时获取数据
这个构建时间是什么时候发生的?
是在我们运行 npm run build 时吗?(构建生产版本)
或者当用户访问我们的 Nextjs 应用程序时?(在每个请求上)
希望有人可以帮助我,也许它可以帮助其他人!
reactjs next.js getserversideprops getstaticprops getstaticpaths
我知道这个话题并不新鲜,我发现(并阅读)了一些讨论。我找不到的是我仍然存在的问题的答案。
其他人如何解决无法在 _app.js 中使用 getStaticProps 的问题?getInitialProps不是我的选择,因为我想使用SSG。即使使用 getInitialProps ,有没有办法强制 SSG?或者我真的必须在每个页面上从我的无头 CMS 中获取我的所有数据吗?例如,因为我想构建一个页眉(包括导航)和一个页脚。目前我看到的唯一选择是重复大量代码。
非常感谢任何提示,感谢您的阅读!
我正在尝试使用以下getStaticProps()方法调试我的页面中包含的 React 组件的方法console.log():
export default class Nav extends React.Component {
render() {
return <nav></nav>;
}
async getStaticProps() {
console.log('i like output, though');
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我既无法在提供应用程序的控制台上看到任何输出,也无法在浏览器的控制台上看到任何输出。我还尝试重新启动yarn dev并运行yarn build以查看它是否会产生输出。唉,没有雪茄。
那么从getStaticProps()and生成和读取调试输出的正确方法是什么 getStaticPaths()?
我使用 Vercel 文档中提供的示例,每 15 秒从 MongoDB 获取一次数据,但不幸的是该函数不起作用。我应该怎么做才能使其按预期工作?
export async function getStaticProps() {
const allData = getSortedData();
const client = await clientPromise;
const isConnected = await client.isConnected();
const alerts = await client.db()
.collection("alerts")
.find({})
.limit(6)
.toArray();
const alertsData = JSON.parse(JSON.stringify(alerts));
return {
props: {
allData,
isConnected,
alertsData
},
revalidate: 15,
};
}
Run Code Online (Sandbox Code Playgroud) 我有一个疑问..我可以在 getStaticProps 中使用 useEffect 吗?
我正在尝试在 getStaticProps 中运行一个函数...它有效..但我不知道这是否是推荐的做法。
useEffect(() => {
remarkBody()
}, [body, blogPostCollection])
Run Code Online (Sandbox Code Playgroud)
如果没有......运行它的最佳方式是什么?
我正在尝试创建一个菜单组件,在构建时读取 pages 文件夹的内容。但是,我没有任何成功。这是我尝试过的:
import path from "path";
import * as ChangeCase from "change-case";
export default class Nav extends React.Component {
render() {
return (
<nav>
{this.props.pages.map((page) => (
<a href={page.link}>{page.name}</a>
))}
</nav>
);
}
async getStaticProps() {
let files = fs.readdirSync("../pages");
files = files.filter((file) => {
if (file == "_app.js") return false;
const stat = fs.lstatSync(file);
return stat.isFile();
});
const pages = files.map((file) => {
if (file == "index.js") {
const name = "home";
const link = "/";
} else …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 [slug].js 通过 getStaticProps 和 getStaticPaths 呈现与 index.js 相邻的页面。使用动态路由导航到页面后,出现不匹配错误。即使提供的路径实际上与页面 slug 和页面道具内容匹配,也会发生此错误。
当 index.js 被复制并重命名为 page-name.js(例如“about.js”)时,页面呈现良好,所以我相信问题在于我如何使用 getStaticPaths。实际上,我并没有完全理解 getStaticProps 和 getStaticPaths 之间的关系。是否有一些映射允许引擎根据地图中的任何路径查找适当的道具?
索引.js
import Link from 'next/link';
import { getPageDataBySlug } from '../lib/api';
export default function Page(pageData) {
const page = pageData;
return (
<>
<h1>document title is: {page.documentTitle}</h1>
<Link href="/[slug]" as="/about">
<a>
<h5>Link to About</h5>
</a>
</Link>
</>
);
}
export async function getStaticProps() {
const props = await getPageDataBySlug('home');
return {
props
};
}
Run Code Online (Sandbox Code Playgroud)
[slug].js
import Link from 'next/link';
import …Run Code Online (Sandbox Code Playgroud) 我正在使用 NextJSgetStaticProps从外部 API 获取一些数据。在阅读有关getStaticProps的数据获取文档时,我遇到了这个特别的说明:
注意:您不应使用 fetch() 在您的应用程序中调用 API 路由。而是直接导入API路由,自己调用它的函数。您可能需要为这种方法稍微重构您的代码。
现在我getStaticProps直接从一个页面组件调用Index,如下所示:
export default function Index({ data }) {
return <div>{data}</div>;
}
export async function getStaticProps() {
const response = await fetch("http://127.0.0.1:8000/data");
const data = await response.json();
return { props: { data } };
}
Run Code Online (Sandbox Code Playgroud)
根据上述文档,不应该这样做。如何重构我的代码以正确获取数据?“导入API路由,自己调用它的函数”是什么意思?
我正在使用启用了打字稿功能的 Next.js
尝试使用此处描述的 getStaticProps https://nextjs.org/docs/basic-features/typescript
使用 GetStaticProps 类型
export const getStaticProps: GetStaticProps = () => {
return {
props: {
host: process.env.DB_HOST.toString(),
},
}
}
Run Code Online (Sandbox Code Playgroud)
Type '() => { props: { host: string; }; }' is not assignable to type 'GetStaticProps<{ [key: string]: any; }, ParsedUrlQuery>'.
Type '{ props: { host: string; }; }' is missing the following properties from type 'Promise<GetStaticPropsResult<{ [key: string]: any; }>>': then, catch, [Symbol.toStringTag], finallyts(2322)
Run Code Online (Sandbox Code Playgroud)
我是打字稿的新手,所以我很难弄清楚它想要什么,
我将不胜感激任何帮助,提前致谢
这是整个页面的代码
import Head from 'next/head'
import styles …Run Code Online (Sandbox Code Playgroud) 我正在尝试 Next.js 并构建一个小应用程序,该应用程序从安装了 GraphQL 的无头 WordPress 应用程序中获取帖子。然后我使用 Apollo/Client 来获取 GraphQL 内容:
apollo-client.js
import { ApolloClient, InMemoryCache } from "@apollo/client";
const client = new ApolloClient({
uri: process.env.WORDPRESS_GRAPHQL_ENDPOINT,
cache: new InMemoryCache(),
});
export default client;
Run Code Online (Sandbox Code Playgroud)
在索引中,我抓住了帖子:
索引.js
import Head from "next/head";
import styles from "../styles/Home.module.css";
import { gql } from "@apollo/client";
import Link from "next/link";
import client from "../apollo-client";
function Home(props) {
const { posts } = props;
return (
<div className={styles.container}>
<Head>
<title>Wordpress blog posts</title>
<meta
name="description"
content="Wordpress blog posts with …Run Code Online (Sandbox Code Playgroud) getstaticprops ×10
next.js ×10
reactjs ×7
debugging ×1
dry ×1
fetch ×1
javascript ×1
menu ×1
mongodb ×1
react-hooks ×1
ssg ×1
typescript ×1
use-effect ×1
vercel ×1