如何使用多语言/多个index.html文件正确设置React Router?

hig*_*nce 2 javascript reactjs react-router-v4 react-router-dom

我正在使用最新的React和React Router版本构建一个Web应用程序,在我的情况下,我的应用程序支持多种语言,并且由于建立了索引,因此每种语言都有单独的html文件。因此,对于像myapp.com这样的网址,

myapp.com/en/-英文

myapp.com/de/-适用于德语等...

在服务器端,每个/ en /文件夹当然都有自己的index.html文件,其中包含以给定语言编写的metatitle和其他元数据,并且它们都可以进入我们的React应用程序(bundle.js

我以前已经使用Router Hash History构建了类似的东西,所以我的应用程序看起来像myapp.com/en/#/home,而我在route.js中的主要路由当然是这样的

<Route path="/" component={MainComponent}
Run Code Online (Sandbox Code Playgroud)

现在,我要使用BrowserRouter,并且如果URL为myapp.com/en/ ,则我的路由应如下所示:

<Link to="/home" />
Run Code Online (Sandbox Code Playgroud)

单击后,将带您到myapp.com/en/home,它将正确呈现在Route中与其链接的组件

 <Route path="/home" exact component={HomeContainer} />
Run Code Online (Sandbox Code Playgroud)

基本上目前这只有在我做了这样的事情时才有效

<Link to=`/${getCurrentLanguage()}/home` /
Run Code Online (Sandbox Code Playgroud)

路线是这样的

<Route path=`/${getCurrentLanguage()}/home` exact component={HomeContainer} />
Run Code Online (Sandbox Code Playgroud)

这当然是最疯狂的

我如何才能达到预期的行为?或者您有其他不同的想法吗?谢谢

编辑我没有问任何关于React翻译的问题,我将使用i18next来翻译React方面,我问的是使用不同index.html文件进行路由的问题

hig*_*nce 5

There are two ways one can approach this

  1. Setting BrowserRouter basename property to the given language

<BrowserRouter basename=`/${getLanguage()}`>
    <Switch>
        <Route path="/" exact component={Home} />
    </Switch>
< /BrowserRouter>
Run Code Online (Sandbox Code Playgroud)

So you can navigate freely with <Link to="/about" />

  1. or use /:lng before any other route

<Switch>
    <Route path="/:lng/" exact component={Home} />
</Switch>
Run Code Online (Sandbox Code Playgroud)