Aip*_*ipi 5 javascript reactjs react-router
我开始在我的应用程序中使用react-router,但我注意到当URL(/url/)末尾带有斜杠时,它不起作用。我对其进行了更多搜索,阅读了所有文档和react-router问题并尝试使用<Redirect from='/*/' to="/*" />,但这不是一个好的解决方案,因为它也无法正常工作。因此,阅读更多内容后,我发现了/?在URL末尾插入的建议,但仍然没有用。
route.js的代码:
export default (
<Route path="/" component={App}>
<IndexRoute component={ProfileFillComponents} />
<Route path="/seguro-residencia" handler={require('./components/Forms/Residencial/ProfileFill/profileFillComponents')} />
<Route path="/seguro-residencia/informacoes-pessoais" component={CotationNumber} />
</Route>
)
Run Code Online (Sandbox Code Playgroud)
index.js的代码:
render((<Router history={browserHistory} routes={routes} />), document.getElementById('root'));
Run Code Online (Sandbox Code Playgroud)
进行更多搜索后,我发现一个人提供了强制在URL末尾加斜杠的功能,然后我决定做出相反的选择,强制不使用斜杠。
使用无尾部斜杠功能更新route.js代码:
export default (
<Route onEnter={forceTrailingSlash} onChange={forceTrailingSlashOnChange}>
<Route path="/" component={App}>
<IndexRoute component={ProfileFillComponents} />
<Route path="/seguro-residencia" handler={require('./components/Forms/Residencial/ProfileFill/profileFillComponents')} />
<Route path="/seguro-residencia/informacoes-pessoais" component={CotationNumber} />
</Route>
</Route>
)
function forceNoTrailingSlash(nextState, replace) {
const path = nextState.location.pathname;
if (path.slice(-1) === '/') {
replace({
...nextState.location,
pathname: path.slice(1,path.lastIndexOf('/')-1)
});
}
}
function forceNoTrailingSlashOnChange(prevState, nextState, replace) {
forceNoTrailingSlash(nextState, replace);
}
Run Code Online (Sandbox Code Playgroud)
再次,这没有用!我需要使这些URL尽可能友好,并且我希望这些URL末尾没有任何斜杠。有什么建议我该怎么做?为什么Redirect在这种情况下不起作用?
删除TrailingSlash.tsx
import React from "react";
import {Navigate, useLocation} from "react-router-dom";
export const RemoveTrailingSlash = ({...rest}) => {
const location = useLocation()
// If the last character of the url is '/'
if (location.pathname.match('/.*/$')) {
return <Navigate replace {...rest} to={{
pathname: location.pathname.replace(/\/+$/, ""),
search: location.search
}}/>
} else return null
}
Run Code Online (Sandbox Code Playgroud)
应用路由.tsx
const AppRoutes: React.FC = () => {
return (
<React.Fragment>
<RemoveTrailingSlash/>
<Routes>
{/* All your routes go here */}
</Routes>
</React.Fragment>
)
}
Run Code Online (Sandbox Code Playgroud)
我找到了一个很好的选择来进行此重定向。下面是我正在使用的代码:
app.use(function(req, res, next) {
if (req.path.length > 1 && /\/$/.test(req.path)) {
var query = req.url.slice(req.path.length)
res.redirect(301, req.path.slice(0, -1) + query)
} else {
next()
}
});
Run Code Online (Sandbox Code Playgroud)
解释基本就是这样:
| 归档时间: |
|
| 查看次数: |
5490 次 |
| 最近记录: |