Ale*_*dro 1 javascript internationalization next.js next-router
我已经为我们的应用程序设置了一些区域设置,它们是uk和us。对于博客,我们可以选择其中之一us/blog,也可以只/blog选择uk区域设置。
当我切换到us这样时:(locale =“us”)
const handleRoute = (locale) => router.push(`${locale}${router.asPath}`)
Run Code Online (Sandbox Code Playgroud)
url 已正确更新为已us/添加。
当我切换回uk使用handleRoute(locale= "") 时,它保持打开状态us,尽管router.asPath等于/blog
完整组件:
export const CountrySelector: React.FC = () => {
const router = useRouter()
const [selectedValue, setSelectedValue] = useState<string>(router.locale)
const handleOnChange = (countryValue) => {
setSelectedValue(countryValue)
}
const handleRoute = (locale) => router.push(`${locale}${router.asPath}`)
const selectedValueLoweredCase = selectedValue.toLowerCase()
const getCountryImageUrl = (countryLabel: string): string =>
`/images/flag-${countryLabel}-sm.png`
const getImageComponent = (countryLabel: string) => (
<Image
htmlWidth="25px"
src={getCountryImageUrl(countryLabel)}
alt={selectedValueLoweredCase}
/>
)
return (
<>
<div data-testid="country-selector">
{console.log(router)}
<Menu>
<MenuButton
as={Button}
variant="countrySelector"
rightIcon={<TriangleDownIcon marginTop="-6px" />}
>
<Flex align="baseline">
<Box
marginRight="12px"
display={selectedValueLoweredCase === "us" ? "none" : "block"}
>
{getImageComponent("uk")}
</Box>
<Box
marginRight="12px"
display={selectedValueLoweredCase === "uk" ? "none" : "block"}
>
{getImageComponent("us")}
</Box>
<Box color={colors.black["100"]}>{selectedValue}</Box>
</Flex>
</MenuButton>
<MenuList padding="0" borderRadius="0">
<MenuOptionGroup
onChange={(countryValue) => handleOnChange(countryValue)}
defaultValue={selectedValue}
type="radio"
>
<MenuItemOption value="UK" color="#000">
<Flex align="baseline">
<Box marginRight="10px">{getImageComponent("uk")}</Box>
<Box
onClick={() => handleRoute("")}
textTransform="uppercase"
color={colors.black["100"]}
>
united kingdom
</Box>
</Flex>
</MenuItemOption>
<MenuItemOption value="US">
<Flex align="baseline">
<Box marginRight="10px">{getImageComponent("us")}</Box>
<Box
onClick={() => handleRoute("us")}
textTransform="uppercase"
color={colors.black["100"]}
>
united states
</Box>
</Flex>
</MenuItemOption>
</MenuOptionGroup>
</MenuList>
</Menu>
</div>
</>
)
}
Run Code Online (Sandbox Code Playgroud)
nextConfig.js:
...
i18n: {
localeDetection: false,
locales: getRegions(), // ["uk", "us"]
defaultLocale: getDefaultRegion(), // "uk"
},
...
Run Code Online (Sandbox Code Playgroud)
使用本地化路由进行路由时,您需要通过在调用中包含其他选项来指定区域设置router.push。
在您的具体情况下,您可以通过在选项中传递所需的区域设置并从路径中省略它来实现:
const handleRoute = (locale) => router.push(router.asPath, router.asPath, { locale: locale })
Run Code Online (Sandbox Code Playgroud)
或者直接在路径中指定它但设置locale为false:
const handleRoute = (locale) => router.push(`${locale}${router.asPath}`, `${locale}${router.asPath}`, { locale: false })
Run Code Online (Sandbox Code Playgroud)
请注意,在这两种情况下,您都需要传递额外的第二个参数as,以便也可以传递选项对象。
| 归档时间: |
|
| 查看次数: |
14938 次 |
| 最近记录: |