使用来自 api 的 id 获取数据,但显示替代文本到地址栏,例如content_title 在 Next.js

Fetch data using an id from an api but display an alternative text to address bar e.g. content_title in Next.js

我使用的 api 只允许使用 id 但不允许 获取数据标题 如下http://0.0.0.0:5000/blog/13b03a39-bc04-4604-baf6-059658f9f5e8 。我想使用 Next Js 将端点 returns a JSON object 呈现给浏览器。但是我想要一个干净的 url 架构,其中包含如下标题 :

而不是包含 id 的 url 如下:

这是我将 props 传递给 Link 的方式:

<Link
    href={`/post/${post.blog_title}`}
    as={`/post/${post.blog_title}`}>
    
    <a className='blog__card--link'>
        <h4 className='blog__card--title'>{post.blog_title}</h4>
    </a>
</Link>

这是我的 [id].js 文件:

import { getBlog } from '../../api/index';

const Article = ({ blog }) => {
    const router = useRouter();

    return (
        <div class='article'>
            <div class='article__main'>
                {/* {console.log(router)} */}
                <ArticleView />
            </div>
        </div>
    );
};

Article.getInitialProps = async (router) => {
    const res = await getBlog(`${router.query.id}`);
    const json = await res.json();
    console.log(json);

    return { blog: json };
};

export default Article;

试图在 getInitialProps 中访问 ${router.query.id} 它 returns 我理解的标题就是我正在经历的 as prop in Link.

是否有可能实现干净的 url 结构,同时在 getInitialProps 中使用 id?以及如何使用 Next.js 中的动态链接实现它?

您需要导入 Next/Router

import { useRouter } from 'next/router'

将您的 getInitialProps 函数更改为

Article.getInitialProps = async (router) => {
    //get id query parameter
    const res = await getBlog(`${router.query.id}`);
    const json = await res.json();
    console.log(json);

    return { blog: json };
};

这应该适合你

https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#context-object

 Article.getInitialProps = async function(context) => {
    const res = await getBlog(`${context.query.id}`);
    const json = await res.json();
    console.log(json);

    return { blog: json };
};

解决方案 1 然而,基于你的端点,我的建议是更改端点以接收 slug,这样你就可以管理你的 slug

解决方案 2 不是最佳实践,但你可以得到干净的 url 并通过 id 使用 Redux

获取数据

解决方案 3 using next-routes 使用 next-routes 并将 id 作为参数传递

<Link route='blog' params={{id: data.id}}>
<a>Hello world</a>
</Link>

我在这个问题上试图实现的是不切实际的,因此我决定在 back-end 中使用独特的 slug 来获取特定数据。

假设您的 article/post 的 link 在其他地方共享,那么获取数据到该 post/article 的唯一方法是使用 slug。