我学习了 nextJS,并尝试使用动态路由和包罗万象的路由。但是我遇到了一个基本问题,我不确定如何在 getStaticPaths 中以数组形式提供数据。
\n这是我当前的代码:
\nimport Link from \'next/link\';\n\nfunction test({ variable }) {\n return (\n <>\n <div>\n <h1>{variable.var}</h1>\n\n <Link href="/">\n <a>\xe2\x86\x90 Back</a>\n </Link>\n </div>\n </>\n );\n}\n\nexport async function getStaticProps({ params }) {\n const variable = params.variable;\n return {\n props: {\n variable,\n },\n };\n}\n\nexport async function getStaticPaths() {\n return {\n fallback: false,\n paths: [\n {\n params: {\n variable: \'testi\',\n },\n },\n ],\n };\n}\n\nexport default test\nRun Code Online (Sandbox Code Playgroud)\n我收到错误:
\nError: A required parameter (variable) was not provided as an array …Run Code Online (Sandbox Code Playgroud) 我正在尝试从一个因 URL 而异的 API 中获取数据,尝试使用 withRouter 来完成它,但它似乎在 getStaticProps 中不起作用。
我目前有以下代码:
export async function getStaticProps({ router }) {
const pageRequest = `http://localhost:3000/api/posts/${router.query.pid}`
const res = await fetch(pageRequest)
const json = await res.json()
return {
props: {
json,
},
}
}
Run Code Online (Sandbox Code Playgroud)
它回来了:
TypeError: Cannot read property 'query' of undefined
Run Code Online (Sandbox Code Playgroud)
获取 URL 中的变量以在 getStaticProps 中使用的正确方法是什么?
部署到 Vercel 时出现以下错误:
Module not found: Can't resolve 'fs' in '/vercel/2d531da8/node_modules/mysql/lib/protocol/sequences'
Run Code Online (Sandbox Code Playgroud)
我不使用依赖 fs,我的 package.json 文件看起来像:
{
"name": "single",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start"
},
"dependencies": {
"mysql": "^2.18.1",
"next": "^9.4.4",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"serverless-mysql": "^1.5.4",
"sql-template-strings": "^2.2.2"
}
}
Run Code Online (Sandbox Code Playgroud)
我对 NextJS 还很陌生,所以我不确定发生了什么。有任何想法吗?
编辑:
对于上下文,我从应用程序中的 mySQL 获取数据,不确定这是否与错误有关
export async function getStaticProps() {
const db = require('./lib/db')
const escape = require('sql-template-strings')
const articles = await db.query(escape`
SELECT *
FROM articles
ORDER …Run Code Online (Sandbox Code Playgroud) next.js ×3