react react-router history模式
React Router 提供了两种路由模式:Hash 模式和 History 模式。
Hash 模式使用 URL 中的 hash(#)来模拟一个完整的 URL,当 URL 中 hash 值发生变化时,页面不会重新加载,而是触发路由变化,React Router 会根据新的 hash 值重新渲染相应的组件。
使用 Hash 模式的示例代码如下:
javascript
import { HashRouter, Route, Switch } from 'react-router-dom';
const App = () => {
  return (
    <HashRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </HashRouter>
  );
}
History 模式使用 HTML5 的 `history` API 来动态修改 URL,而不会像 Hash 模式那样在 URL 中添加 #,这样可以更加美观。但是,使用 History 模式需要服务端的支持。当用户访问一个路由时,服务端需要始终返回同一份 HTML,并在服务端根据路由配置来渲染相应的组件。
使用 History 模式的示例代码如下:reactrouter6路由拦截
javascript
import { BrowserRouter, Route, Switch } from 'react-router-dom';
const App = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/about" component={About} />
        <Route path="/contact" component={Contact} />
      </Switch>
    </BrowserRouter>
  );
}
无论是使用 Hash 模式还是 History 模式,React Router 都提供了相同的 API 来定义路由和渲染组件。只需根据需要选择一种适合的模式即可。