我已经偶然发现了一个与之相关的错误。首先,React-router
我认为该错误仅存在于我的网站中。然后我发现使用ReactJS的大型公司也存在相同的问题。
如果您在网址中写了多个斜杠,然后按Enter,您将看到(小)网站显示header
和footer
。
巨型项目的行为将是异常的,某些组件将被破坏,其中一些将不会显示。
这个项目的例子。
因此,我尝试清理我的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进行测试。如果您在网址中写了多个斜杠,它将仅显示组件列表。如何解决?
考虑一下,这是您的替代品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] 删除。
我来说两句