Can not do multilingual website relying on React Router

人盡茶涼 提交于 2020-01-06 18:32:49

问题


I'm trying to make a multilingual SPA with React and to rely on React-Router.

Here is a simplified version of the entry file:

// define the routes for each language ..
const InnerRoutes = (
    <Route>
        <IndexRoute page="home" component={InnerPage}></IndexRoute>
        <Route path="(:page)" component={InnerPage}></Route>
    </Route>
);

// define the routes for all the languages, using InnerRoutes .. 
const AllRoutes = (
    <Router history={browserHistory}>
        <Route path='/' component={App} language="bg">
            {InnerRoutes}
            <Route path="en" language="en">
                {InnerRoutes}
            </Route>
        </Route>
    </Router>
);

// and render our app ..
ReactDOM.render(
    AllRoutes,
    document.getElementById('app')
);

So, I have the App top-level component and the InnerPage component.

The issue is:

  1. When navigation change happens - InnerPage updates and (eventually) re-renders.

Inside InnerPage:

  1. I have access to the requested page via the page property.
  2. Unfortunately - I don't have access to the language property.

And that's why InnerPage can't pull the data from an end point - it knows the page, but not the language.


回答1:


The router passes a routes prop to all route components, which is the set of matched routes. For example, on /, it would look something like this: [{ path: '/', language: 'bg'}, { }, { page: 'home' }].

So, depending on how you want to deal with the cases of having none or multiple languages declared by different matched routes, you can do something like this:

const lang = this.props.routes.reduce((lang, route) => { 
  return route.language || lang;
}, defaultLang);

which would prioritize the language given by inner routes.

Looking at your route config, there are two more things I should mention:

  1. In your InnerRoutes, the page values for <IndexRoute page="home" ... /> and <Route path="(:page)" ... /> are exposed differently. The former is a prop on a route (like language) and can be accessed via this.props.route.page, while the latter is a URL param (this.props.params.page).

  2. The English <IndexRoute> is not reachable, because the Bulgarian :page route comes before and matches as well. You can fix this by moving the English routes up.

Here's a jsbin demonstrating the points I mentioned: http://jsbin.com/siqake/5/edit?js,output



来源:https://stackoverflow.com/questions/40510303/can-not-do-multilingual-website-relying-on-react-router

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!