【问题标题】:Dynamic route segment in nextJS static js buildnextJS 静态 js 构建中的动态路由段
【发布时间】:2020-10-09 18:54:09
【问题描述】:

是否可以在静态构建上下文中使用带有 nextJS 的动态路由路径?

假设我的构建是一组 html、js、css 资产,可以托管在任何 Web 服务器(Apache、Nginx、S3、Netlify 等)上。

例如,我定义了一个路径/pages/[article].js/read,我希望能够使用以下结构:/page/articleA/read,其中articleA 是一个动态变量。

如果可行,如何实现?

【问题讨论】:

    标签: reactjs redirect browser routes next.js


    【解决方案1】:

    是的,在使用带有 nextjs 的静态站点生成时可以使用动态路由。您必须使用数据获取方法getStaticProps 根据动态路由参数获取所需的数据。此外,您必须使用另一个函数getStaticPaths 来生成paths 列表,nextjs 将在构建时为其构建静态页面。例如,

    假设页面/pages/articles/[articleId].js,您可能会看到以下伪代码。

    // you have to generate and return a list of paths 
    export const getStaticPaths = async () => {
        const articles = await /*Fetch the articles from backend or make a db query*/
        const paths = articles.map(article => ({ params: { articleId: article.id }}));
    
        return {
           paths,
           fallback: false
        }
    }
    
    
    export const getStaticProps = async (ctx) => {
       const articleId = ctx.params.articleId;
    
    
       // fetch the data using the article id and return as props
    
      return {
         props: /* fetched data */
    
      }
    }
    
    // create the page component and export it as the default export
    

    您可以在docs 中了解更多信息。请记住,因为fallback 设置为false,nextjs 将为函数getStaticPaths 未返回的任何路径显示404 页面,您可以阅读有关fallback here 的信息。

    【讨论】:

    • 谢谢,将测试它,这可能是解决方案
    • 是的,当然。这是来自nextjs repo 的example,它使用 SSG(static-site-generation) 以及可能与您的用例类似的动态路由。让我知道它是否有任何帮助,或者您在实施它时是否有任何问题。
    猜你喜欢
    • 2020-12-19
    • 1970-01-01
    • 2020-09-01
    • 2021-08-09
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 2022-06-12
    • 2020-09-08
    相关资源
    最近更新 更多