【问题标题】:Can i create a Nextjs dynamic route [id]-[first_name]-[last_name]?我可以创建 Nextjs 动态路由 [id]-[first_name]-[last_name] 吗?
【发布时间】:2022-12-30 13:01:57
【问题描述】:

我正在使用 nextjs 来构建目录。我实际上想单击“更多信息”和一个信息页面以加载到 /info/[id]-[first_name]-[last_name] 的 URL 下。 我通过 id 从 api 中提取数据,然后它将获取 first_name 和 last_name 数据。

我在名为 [id]-[first_name]-[last_name] 的信息文件夹中有一个文件:

export default function Info({ info }) {
return (
    <div>
        <h1>First Name</h1>
        <p> Last Name </p>
    </div>
    );
}

export const getStaticPaths = async () => {
const res = await fetch('http://xxx:1337/api/info');
const data = await res.json();

// map data to an array of path objects with params (id)
const paths = [data].map(info => {
    return {
        params: [{
            id: `${info.id}-`,
            first_name: `${info.first_name}-`,
            last_name: `${info.last_name}`
        }]
    }
})

return {
    paths,
    fallback: false
    }
}

export const getStaticProps = async (context) => {
const id = context.params.id;
const res = await fetch('http://xxxx:1337/api/info/' + id);
const data = await res.json();

return {
    props: { info: data }
}

有了这个我就得到了错误:

错误:/info/[id]-[first_name]-[last_name] 的 getStaticPaths 中未提供必需参数 (id]-[first_name]-[last_name) 作为字符串

我想这个错误是不言自明的,但此时我被阻止了。我已经看到我可以使用 slug,但这意味着要重新处理很多 api。

对此的任何方向表示赞赏。谢谢!

【问题讨论】:

标签: next.js url-routing


【解决方案1】:

这样你就可以捕获所有属性/info/[id]/[first_name]/[last_name] 通过制作文件/info/[...slug]

export const getStaticProps = async ({ query }) => { 
         const [id ,firstname ,lastname] = query.slug }

或者保留它/info/[slug],然后将它作为字符串获取,然后你可以拆分它

【讨论】:

    猜你喜欢
    • 2012-07-18
    • 2021-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 2020-02-11
    • 1970-01-01
    • 1970-01-01
    • 2021-04-01
    相关资源
    最近更新 更多