反应路由器前缀

时间:2019-01-30 12:24:35

标签: reactjs react-router

我正在React中建立一个多语言站点,并且正在使用React Router进行路由。现在,我将其设置为必须存在前缀才能过渡到路由。

我想要做的是以下操作:当我进入 localhost:3000 时,我希望我的应用程序过渡到home组件。当我去 localhost:3000 / jp 我仍然想过渡到home组件,除了现在我的语言前缀是 jp

我希望英语成为默认语言,而对于其他语言,它们必须出现在前缀中。 现在,仅当我输入 localhost:3000 / en 时,它才会转换到home组件。

有没有办法做到这一点?

import React, { Component } from 'react';
import { Route, Switch } from "react-router-dom";

import { Home } from '../containers/home';
import { About } from '../containers/about';
import { Contact } from '../containers/contact';


export default class Routes extends Component {
    render(){
        return(
            <Switch>
                <Route path="/:lang/about" component={About} />
                <Route path="/:lang/contact" component={Contact} />
                <Route path="/:lang/" component={Home} />
            </Switch>
        );
    }
}

1 个答案:

答案 0 :(得分:1)

只需在末尾添加一个Redirect即可,如果没有其他操作,它将被匹配,它将重定向到/en

import React, { Component } from 'react';
import { Route, Switch, Redirect } from "react-router-dom";

import { Home } from '../containers/home';
import { About } from '../containers/about';
import { Contact } from '../containers/contact';


export default class Routes extends Component {
    render(){
        return(
            <Switch>
                <Route path="/:lang/about" component={About} />
                <Route path="/:lang/contact" component={Contact} />
                <Route path="/:lang/" component={Home} />
                <Redirect to="/en" />
            </Switch>
        );
    }
}

演示在https://codesandbox.io/s/18rm8k82lj


更新后的答案(要发表评论

问题在于/:lang/将与/about匹配,并且lang将被设置为about

一种解决方案是使用路线的render道具并决定您要在此处做什么

export default class Routes extends Component {
  render() {
    const supportedLanguages = ["en", "jp", "de", "es"];
    return (
      <Switch>
        <Route path="/:lang/about" component={About} />
        <Route path="/:lang/contact" component={Contact} />
        <Route
          path="/:lang/"
          render={props =>
            supportedLanguages.includes(props.match.params.lang) ? (
              <Home {...props} />
            ) : (
              <Redirect to={`/en/${props.match.params.lang}`} />
            )
          }
        />
      </Switch>
    );
  }
}

演示在https://codesandbox.io/s/k2n9997345