使用React Router的网站中的斜线问题

光谱

我已经偶然发现了一个与之相关的错误。首先,React-router我认为该错误仅存在于我的网站中。然后我发现使用ReactJS的大型公司也存在相同的问题。

如果您在网址中写了多个斜杠,然后按Enter,您将看到(小)网站显示headerfooter

巨型项目的行为将是异常的,某些组件将被破坏,其中一些将不会显示。

这个项目的例子。

奇迹制作的Airbnb

因此,我尝试清理我的URL。

if (window.location.pathname.length > 1) {
      // const url = window.location.pathname.slice(0, 1);
      const url = window.location.pathname.replace(/\/\//g, "");
      history.push(`${url}`);
}

我不知道为什么这个尝试不起作用。

Codesandbox进行测试。如果您在网址中写了多个斜杠,它将仅显示组件列表。如何解决?

苏丹·H

考虑一下,这是您的替代品Main

  • 它将修复双斜线或更多的斜线。
  • 它修复了每个路线的静态渲染,使其仅作为组件。

完整的CodeSaneBox

import React, { Component } from "react";
import { Switch, Route } from "react-router-dom";
import { withRouter } from "react-router-dom";
import Home from "./Home";
import Roster from "./Roster";
import Schedule from "./Schedule";

// The Main component renders one of the three provided
// Routes (provided that one matches). Both the /roster
// and /schedule routes will match any pathname that starts
// with /roster or /schedule. The / route will only match
// when the pathname is exactly the string "/"

class Main extends Component {
  componentDidMount() {
    this.fixDoubleSlash();
  }

  // Will check for double slashes and redirect to the correct path.
  fixDoubleSlash = () => {
    const {
      location: { pathname },
      history: { push }
    } = this.props;

    if (pathname.match(/\/{2,}/g)) {
      push(pathname.replace(/\/{2,}/g, "/"));
    }
  };

  render() {
    return (
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/roster" component={Roster} />
        <Route path="/schedule" component={Schedule} />
      </Switch>
    );
  }
}

export default withRouter(Main);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章