reactjs – 无法在React路由器中正确添加前缀到路径
发布时间:2020-12-15 20:19:55 所属栏目:百科 来源:网络整理
导读:我正在创建多语言应用程序.我正在使用:React Intl; React Router(最新版本v4);终极版. ?我的应用中的路径将取决于区域设置: / -- default expecting this to be uk/en/ru/news -- uk/en/news/ru/news 如果用户有locale = en-US并输入localhost:8080 app将
我正在创建多语言应用程序.我正在使用:React Intl; React Router(最新版本v4);终极版.
?我的应用中的路径将取决于区域设置: / <-- default expecting this to be uk /en /ru /news <-- uk /en/news /ru/news 如果用户有locale = en-US并输入localhost:8080 app将他重定向到localhost:8080 / en 如果用户具有locale = uk并输入localhost:8080 app会显示与地址localhost:8080 /对应的组件,而不更改位置路径名. Routers.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); 目前它没有按预期工作. 解决方法
这是我解决问题的方法.
重定向工作正常,前缀添加到道具中. Routers.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} /> )} /> ); 标题组件(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); } }; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |