我正在 React 中构建一个多语言站点,并且我正在使用 React 路由器进行路由。现在我已经设置了前缀必须存在才能转换到路由。
我想要做的是以下内容:当我转到 localhost:3000 时,我希望我的应用程序转换到 home 组件。当我去
localhost:3000/jp 除了现在我的语言前缀是 jp 我仍然想转换到 home 组件。
我希望英语是默认语言,而对于其他语言,它们必须出现在前缀中。
现在,如果我输入 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>
);
}
}
最佳答案
只需添加一个 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
关于reactjs - react 路由器前缀,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54440612/