gpt4 book ai didi

javascript - 链接组件在位置相同时更新浏览器历史记录

转载 作者:行者123 更新时间:2023-11-30 06:50:24 25 4
gpt4 key购买 nike

我用的是 react router v 4.3.1当我多次单击主页链接时,每次单击都会创建一个新的历史记录项。每次都会重新呈现主页。现在您的浏览器导航已损坏(后退/前进按钮无法按预期工作)。

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

const Example = () => (
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/">Home 1</Link></li>
<li><Link to="/">Home 2</Link></li>
<li><Link to="/about">About</Link></li>
<li><Link to="/topics">Topics</Link></li>
</ul>

<hr />

<Route exact path="/" render={()=><p>Home</p>} />
<Route path="/about" render={()=><p>about</p>} />
<Route path="/topics" render={()=><p>topics</p>} />
</div>
</Router>
);

render(<Example />, document.body);

求助,如何解决这个问题?

最佳答案

这是 React Router v4 引入的一个已知的老问题,目前(据我所知)尚未解决。

幸运的是,使用自定义历史对象很容易解决问题(如果您想使 Redux 状态与浏览器历史保持同步,您也会这样做)。真正的生产代码应该比我在这里写的更健壮,但你可以从这里开始:

a) 首先使用 <Router>而不是 <BrowserRouter> .

import { Router, Route, Link } from "react-router-dom";

b) 创建您自己的历史记录对象(如果您没有创建,请务必 npm add history):

import createBrowserHistoryfrom "history/createBrowserHistory";

// ...

const history = createBrowserHistory();

c) 替换 push()使用您自己的实现方法:

const originalHistoryPush = history.push;

history.push = function(path, state = {}) {
if (!this.location) {
originalHistoryPush(path, state);
return;
}

const oldPath = this.location.pathname + this.location.search + this.location.hash;
if (oldPath !== path || !shallowEqual(state, this.location.state)) {
originalHistoryPush(path, state);
} else {
this.replace(path, state);
}
};

d) 使用自定义历史:

<Router history={history}>...</Router>

请注意,我使用的是假设的 shallowEqual()比较的方法。您可以快速编写自己的实现或从众多实现中选择一种。

关于javascript - 链接组件在位置相同时更新浏览器历史记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54252787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com