问题
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:
- When navigation change happens -
InnerPage
updates and (eventually) re-renders.
Inside InnerPage
:
- I have access to the requested page via the
page
property. - 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:
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 (likelanguage
) and can be accessed viathis.props.route.page
, while the latter is a URL param (this.props.params.page
).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