Reactjs 将react路由器转换为v4:重定向所有路由以包括lang
我们已经本地化了我们的应用程序,现在我需要在所有路由中包含lang,我遇到了一些代码,它们可以实现我想要的功能,但在react router v4中却很难实现同样的功能 这是我引用的代码 下面是我正在使用的示例代码,在将其集成到我们的应用程序之前,我将使用该代码使其正常工作:Reactjs 将react路由器转换为v4:重定向所有路由以包括lang,reactjs,react-router,react-router-v4,react-router-dom,Reactjs,React Router,React Router V4,React Router Dom,我们已经本地化了我们的应用程序,现在我需要在所有路由中包含lang,我遇到了一些代码,它们可以实现我想要的功能,但在react router v4中却很难实现同样的功能 这是我引用的代码 下面是我正在使用的示例代码,在将其集成到我们的应用程序之前,我将使用该代码使其正常工作: // add lang to url if it's not present function langRedirect(props) { console.log({ props }); const defaul
// add lang to url if it's not present
function langRedirect(props) {
console.log({ props });
const defaultLang = 'en';
const redirectPath = `/${defaultLang}${props.history.location.pathname}`;
console.log(redirectPath);
props.history.replace({ pathname: redirectPath, });
}
测试。。。什么都不做}>
Test}/>
Test2}/>
这里发生的情况是,如果我走到像
/test
这样的路线,即使最后没有/阻止使用langRedirect
去路线,交换机仍然会捕捉/:lang/
路线。在v4中似乎是一种不同的行为。好吧,在花了几个小时在这上面之后,我碰巧在发布了这个问题之后就明白了
我不得不向路由添加一个*,就像这样Test}>
以下是工作代码:
// add lang to url if it's not present
function langRedirect(props) {
console.log({ props });
const defaultLang = 'en';
const redirectPath = `/${defaultLang}${props.history.location.pathname}`;
console.log(redirectPath);
props.history.replace({
pathname: redirectPath,
});
}
const TestingRoutes=()=>{
返回(
测试}>
Test}/>
Test2}/>
);
};
好吧,花了几个小时在这上面之后,我碰巧在发布了这个问题之后就明白了
我不得不向路由添加一个*,就像这样Test}>
以下是工作代码:
// add lang to url if it's not present
function langRedirect(props) {
console.log({ props });
const defaultLang = 'en';
const redirectPath = `/${defaultLang}${props.history.location.pathname}`;
console.log(redirectPath);
props.history.replace({
pathname: redirectPath,
});
}
const TestingRoutes=()=>{
返回(
测试}>
Test}/>
Test2}/>
);
};
const TestingRoutes = () => {
return (
<Switch>
<Route exact path="/:lang/*" render={() => <h1>Test</h1>}>
<Route path="/:lang/test" render={() => <h2>Test</h2>} />
<Route path="/:lang/test2" render={() => <h2>Test2</h2>} />
</Route>
<Route path="*" render={langRedirect} />
</Switch>
);
};