如何在React-Router URL中删除尾部斜杠

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在这种情况下不起作用?

mle*_*ter 8

React Router v6 解决方案

删除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)


Aip*_*ipi 3

我找到了一个很好的选择来进行此重定向。下面是我正在使用的代码:

   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)

解释基本就是这样:

  1. 在此函数中,我验证 URL 是否大于等于 1,以及是否有尾部斜杠。
  2. 如果为 true,我会获取不带尾部斜杠的 URL,并进行 301 重定向到不带尾部斜杠的此页面。
  3. 否则,我跳转到下一个方法来发送值。

  • 国家不参与这个过程。它是服务器端的。因此,它不会干扰您的申请。您可以将其路由传递给 URL,而无需尾随斜杠。这只是客户端点击的情况。要在路由中实现此功能,您可以使用“react-route”并进行如下操作:`&lt;Route path="/your-url-extension" component={ProfilePage} /&gt;`,而不使用尾部斜杠。它不会导致您的应用程序出现任何错误。祝你好运! (2认同)