next.js 接下来是索引的动态路由,tsx ssr

hfsqlsce  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(108)

我已经在接下来设置了一些区域设置。config.js
i18n: { locales: ["en", "en-us", "en-gb", "en-au", "en-ca", "en-ie", "es-es", "es-co", "es-ar", "es-pe", "es-ve", "es-cl", "es-ec", "es-bo"], defaultLocale: "en", },
以及变量export const locales= ["en", "en-us", "en-gb", "en-au", "en-ca", "en-ie", "es-es", "es-co", "es-ar", "es-pe", "es-ve", "es-cl", "es-ec", "es-bo"];
对于每一个地区,我想有一个单独的索引文件。现在我已经在pages/index.tsx旁边设置了pages/[locale].tsx
in [locale].TSX我有这个设置。

import { getArticles } from "../utils/db/serverDb";
import ArticlesHome from "@/components/home/ArticlesHome";
import {  locales } from "@/utils/staticInfo";

export default function Home(props: { [key: string]: string }) {
  const articles: { [key: string]: any } = JSON.parse(props.articles);

  return (
    <>
      <main className={styles.main}>
        <div className={styles.articleWrapper}>
          <ArticlesHome articles={articles} />
        </div>
      </main>
    </>
  );
}

export async function getStaticProps({ locale }: { locale: string }) {
  //get country initials from locale
  const country = locale !== "en" ? locale.split("-")[1] : "gb";
  //get number of articles from required country
  const articles = await getArticles(`${country}`, 3);
  return {
    props: {
      articles,
    },
    revalidate: 3600,
  };
}

export async function getStaticPaths() {
     let paths:{[params:string]: {[locale:string]:string}}[] = [];

     locales.forEach((locale) => {
       // generate paths for each locale
       paths.push({ params: { locale: locale } });
     });
  return {
    paths,
    fallback: false,
  };
}

我需要为索引设置什么。tsx?应该只是重定向吗?目前我有索引。tsx与[locale]相同。tsx,并且当它构建时,它将路径构建为en/en、en/en-gb/、en/en-ir、en/es-es等。我以为是en,en-gb,en-ir等等..
这一切都工作,但我认为有一些真的很糟糕,因为我不知道如何处理索引。tsx里面应该有什么,为什么它要用所有其他的语言环境来构建默认的语言环境
我试着在谷歌上寻找解决方案,并与chatGPT交谈,但我所能找到的是关于如何做动态页面的文章,如帖子/[文章]。js和chat给出的代码不起作用。我无法找到一个解决方案如何动态设置索引。

anhgbhbe

anhgbhbe1#

重定向到动态路径

你可以尝试将服务器端重定向与获取静态路径和创建一个动态文件相结合。[locale]。tsx或[locale]/index。tsx解决方案应该是在getStaticProps中重定向。来自文件:

export async function getStaticProps(context) {
  const res = await fetch(`https://...`)
  const data = await res.json()

  if (!data) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
        // statusCode: 301
      },
    }
  }

  return {
    props: { data }, // will be passed to the page component as props
  }
}

但是请记住,您需要手动从URL中删除i18 n前缀,您可以在useEffect中删除它或寻求其他解决方案,因为这是正确的i18 n行为。

i18N

也许你的结构对于你想要实现的目标来说有点短。
它是如何工作的--它为每个路由添加前缀,包括动态路由,并将locale传递给上下文,这样你就可以处理来自源的正确版本的内容。所以每个路由例如pages/index。tsx将包含所有带有****“/en、/en-gb等的页面版本。”““只要你把它放在那里。tsx它生成以下路由路径“/en,/en-gb。..”,并且由于您还启用了i18 n,因此它也将使用前缀来创建此路由。
最后,如果你的要求不严格,你可以创建一些其他的父母,例如。/articles.
代码将类似于您的代码,但没有getStaticPaths。因为所有区域设置路径都将由i18 n处理。

import { getArticles } from "../utils/db/serverDb";
import ArticlesHome from "@/components/home/ArticlesHome";
import {  locales } from "@/utils/staticInfo";

export default function Articles(props: { [key: string]: string }) {
  const articles: { [key: string]: any } = JSON.parse(props.articles);

  return (
    <>
      <main className={styles.main}>
        <div className={styles.articleWrapper}>
          <ArticlesHome articles={articles} />
        </div>
      </main>
    </>
  );
}

export async function getStaticProps({ locale }: { locale: string }) {
  //get country initials from locale
  // HERE You Will handle the load of localized articles.
  const country = locale !== "en" ? locale.split("-")[1] : "gb";
  //get number of articles from required country
  const articles = await getArticles(`${country}`, 3);
  return {
    props: {
      articles,
    },
    revalidate: 3600,
  };
}

又一次进攻

看起来您希望为每个区域设置一个单独的索引文件,并根据用户的区域设置提供正确的索引文件。您可以提供一个索引文件,并根据用户的区域设置使用服务器端重定向到正确的区域设置索引文件,而不是为每个区域设置单独的索引文件。
要实现这一点,您可以更新pages/[locale]/index。tsxpages/[locale]。tsx文件使用getServerSideProps函数执行服务器端重定向。并在getStaticProps或getServerSideProps中添加重定向。
以下是如何修改索引。tsx文件:

import { GetServerSideProps } from 'next';
import { useRouter } from 'next/router';
import { useEffect } from 'react';

const IndexPage = () => {
  const router = useRouter();

  useEffect(() => {
    router.replace(`/${router.locale}`);
  }, [router]);

  return null;
};

export default IndexPage;

export const getServerSideProps: GetServerSideProps = async (context) => {
  const { locale } = context;
  return {
    redirect: {
      destination: `/${locale}`,
      permanent: false,
    },
  };
};

此安装程序将根据用户的区域设置执行到正确区域设置索引文件的服务器端重定向。它会将用户重定向到相应的[locale]。tsx页面,当他们访问您的站点的根路径。
确保从index中删除getStaticProps和getStaticPaths函数。tsx,因为在此设置中不需要它们。仅在[locale]中保留这些函数。tsx文件。
请记住,下一步中的i18 n模块。js被设计为处理国际化,而locale路径用于根据用户的locale提供内容。虽然这两个概念是相关的,但在配置应用程序时不要混淆它们,这一点很重要。在您的例子中,对i18 n模块使用服务器端重定向应该有助于实现所需的行为。此外,“en/en,en/en-gb/,en/en-ir,en/es-es”的行为也是预期的,因为i18 n模块是从文档中预先添加区域设置的:https://nextjs.org/docs/advanced-features/i18n-routing
阅读子路径路由章节。

相关问题