我正在创建多语言应用程序。我正在使用:React Intl; React Router(最新 v4);终极版。
我的应用程序中的路径将取决于区域设置:
/ <-- default expecting this to be uk
/en
/ru
/news <-- uk
/en/news
/ru/news
如果用户有 locale = en-US
并输入 localhost:8080
应用程序会将其重定向到 localhost:8080/en
如果用户有 locale = uk
并输入 localhost:8080
应用程序会向他显示与地址 localhost:8080/
对应的组件,而无需更改位置路径名。
路由器.jsx
const Routes = ({ lang }) => (
<BrowserRouter basename={lang}>
<Route render={props => <Header {...props} />} />
<Switch>
<Route exact path={`/:${lang}`} component={Landing} />
<Route exact path={`/:${lang}/news`} component={News} />
<Route component={FourOhFour} />
</Switch>
</BrowserRouter>
);
const mapStateToProps = state => ({ lang: getLang(state.locale) });
export default connect(mapStateToProps)(Routes);
目前它没有按预期工作。
如果我输入 localhost:8080/
或 localhost:8080/en
,我在路由配置中遇到 no match
。
最佳答案
这是我的解决方法。 重定向正在运行,并且前缀已添加到 props 中。
路由器.jsx
const Routes = ({ lang }) => (
<BrowserRouter>
<Route render={props => <Header lang={lang} {...props} />} />
<Switch>
<RootRouter
exact
path={'/:lang(en|ru)?'}
lang={lang}
component={Landing}
/>
<Route
exact
path={'/:lang(en|ru)?/news'}
render={props => <News {...props} lang={lang} />}
/>
<Route component={FourOhFour} />
</Switch>
</BrowserRouter>
);
const mapStateToProps = state => ({ lang: getPrefix(state.locale) });
export default connect(mapStateToProps)(Routes);
RootRouter.jsx
const RootRouter = ({ component: Component, exact, path, lang }) => (
<Route
exact={exact}
path={path}
render={(props: ContextRouter) =>
props.location.pathname === '/' && lang !== '' ? (
<Redirect to={`/${lang}`} />
) : (
<Component {...props} lang={lang} />
)}
/>
);
header 组件 (Contacts.jsx) 中更改 Click 事件区域设置的方法:
const changeLang = newLang => () => {
if (lang !== newLang) {
const newUrl = switchLangHepler(lang, newLang, location.pathname);
setLocaleData(newLang);
localStorage.setItem('lang', String(newLang));
history.replace(newUrl);
}
};
关于reactjs - 无法在 React 路由器中正确添加前缀到路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46113765/