问题描述
语言环境更改在我的 next.js 应用程序中运行良好,除了动态路由。在浏览器地址栏中,我确实得到了从 http://localhost:3000/client/home/profile
到 http://localhost:3000/de/client/home/profile
的转换,但是页面给出了 404 错误...
我的动态页面[tab].tsx
import router from 'next/router'
import dynamic from 'next/dynamic'
import styled from 'styled-components'
import {useTranslation,i18n} from 'next-i18next'
import {useEffect,useState,useContext} from 'react'
import {serverSideTranslations} from 'next-i18next/serverSideTranslations'
import Layout from 'layouts'
import {DB,PATH} from 'utils/constants'
import {GlobalContext} from 'utils/contexts'
import {Tabs,LanguageSelector} from 'components/ui'
import {ChartData,ChartDataPoint,UsageStats} from 'utils/types'
import {getData,toTitleCase,isClient,emailVerified} from 'utils/helpers'
const Docs = dynamic(() => import('components/client/docs'))
const Stats = dynamic(() => import('components/client/stats'))
const Profile = dynamic(() => import('components/client/profile'))
const Tab = ({tab}) => {
const {t} = useTranslation()
return (
<Layout>
<LanguageSelector />
<Tabs
basePath={'/client/home'}
tab={tab}
tabs={[
{
slug: 'stats',label: t('client.home.stats'),component: <Stats data={data} />
},{
slug: 'profile',label: t('client.home.profile'),component: <Profile client={client} />
},{
slug: 'docs',label: t('client.home.docs'),component: <Docs />
}
]}
/>
</Layout>
)
}
export const getStaticProps = async ({params,locale}) => ({
props: {
tab: params.tab,...await serverSideTranslations(locale)
}
})
export const getStaticPaths = async () => {
return {
paths: [
{params: {tab: 'stats'}},{params: {tab: 'profile'}},{params: {tab: 'docs'}}
],fallback: false
}
}
export default Tab
我在 LanguageSelector.tsx 中进行区域设置切换:
import router from 'next/router'
import {i18n} from 'next-i18next'
import {useState,useEffect} from 'react'
import {Select} from '.'
import {LANGUAGES} from 'utils/constants'
export const LanguageSelector = () => {
const [locale,setLocale] = useState(i18n.language)
useEffect(() => {
const {pathname,asPath,query} = router
router.push({pathname,query},{locale})
},[locale])
return (
<Select
borderless
isSearchable={false}
value={i18n.language}
options={LANGUAGES.filter(language => language !== i18n.language)}
onValueChange={setLocale}
/>
)
}
知道我的错误在哪里吗?
解决方法
如果您将 getStaticPaths
与内置 Next.js i18n 路由一起使用,那么您还需要返回带有路径的区域设置键,如下所示:
export const getStaticPaths = ({ locales }) => {
return {
paths: [
{ params: { slug: 'post-1' },locale: 'en-US' },{ params: { slug: 'post-1' },locale: 'fr' },],fallback: true,}
}