reactjs - 无法在 React 路由器中正确添加前缀到路径

标签 reactjs react-redux react-router-v4 react-intl

我正在创建多语言应用程序。我正在使用: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/

相关文章:

reactjs - 在 React 中,如何在所有组件中拥有一个自定义钩子(Hook)的单个实例?

reactjs - React 上的路由参数中允许使用斜杠

reactjs - 重新加载或手动输入 URL 始终重定向到 root

javascript - Redux 状态修改不会在调度后立即反射(reflect)出来。调度是异步的吗?

javascript - 这么多括号。我真的无法理解所有这些括号

javascript - 在 React 中处理滚动动画

reactjs - 如何使用react-redux-firebase从firestore获取子集合

reactjs - 使用查询字符串触发 Redux/React Router 中的操作

css - 我需要访问 InputGroup BlueprintJs react 组件中的输入

javascript - 在 react 渲染中调用格式化函数是不好的做法吗?