Minimal reproducible example на основе примера
package.json
{
"name": "React Router - No Match (404)",
"version": "0.0.0",
"description": "A simple example deployed using react-codesandboxer",
"main": "index.js",
"dependencies": {
"react-router-dom": "^5.3.0",
"react-scripts": "latest",
"react": "latest",
"react-dom": "latest",
"history": "latest"
}
}
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './example';
ReactDOM.render(
<App />,
document.getElementById('root')
);
example.js
import React from "react";
import {
HashRouter as Router,
Route,
Link,
Switch,
Redirect
} from "react-router-dom";
import { createHashHistory } from "history";
// You can use the last <Route> in a <Switch> as a kind of
// "fallback" route, to catch 404 errors.
//
// There are a few useful things to note about this example:
//
// - A <Switch> renders the first child <Route> that matches
// - A <Redirect> may be used to redirect old URLs to new ones
// - A <Route path="*> always matches
export default function NoMatchExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/old-match">Old Match, to be redirected</Link>
</li>
<li>
<Link to="/will-match">Will Match</Link>
</li>
<li>
<Link to="/will-not-match">Will Not Match</Link>
</li>
<li>
<Link to="/also/will/not/match">Also Will Not Match</Link>
</li>
</ul>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/old-match">
<Redirect to="/will-match" />
</Route>
<Route path="/will-match">
<WillMatch />
</Route>
<Route path="*">
<NoMatch />
</Route>
</Switch>
</div>
</Router>
);
}
function Home() {
return <h3>Home</h3>;
}
function WillMatch() {
return <h3>Matched!</h3>;
}
let history = createHashHistory();
function goToMain() {
history.push("/");
}
function NoMatch() {
let location = history.location;
return (
<div>
<h3>
No match for <code>{location.pathname}</code>
</h3>
<button onClick={goToMain}>Go home</button>
</div>
);
}
Если нажать ссылку Will Not Match, а затем кнопку Go home, якорь в адресной строке браузера обновится, а страница не перерисуется.
Если поменять версию history на 4.10.1, как сказано здесь, то от перехода по ссылкам location.pathname перестанет обновляться.
Что я делаю не так? Неужто все так, это библиотека не так написана?