Jir*_*Jir 6 reactjs react-router
我正在 React 中构建一个多语言站点,并且我正在使用 React 路由器进行路由。现在我已经设置了前缀必须存在才能转换到路由。
我想要做的是以下内容:当我转到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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
只需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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
演示在https://codesandbox.io/s/18rm8k82lj
更新的答案(由于评论)
问题是/:lang/will 匹配/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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
演示在https://codesandbox.io/s/k2n9997345
| 归档时间: |
|
| 查看次数: |
6848 次 |
| 最近记录: |