Dar*_* K. 6 javascript reactjs react-router
如果当前页面是site.com/one并且我正在点击<Link to='/one'>One</Link>,它会在每次点击时将新项目推送到历史记录(但位置不会改变)。如何防止?这真是愚蠢的行为。
问题 #470中也描述了此问题。将来可能会修复。同时,您可以使用自己的链接组件,该组件replaceState在位置与当前位置匹配时执行以下操作:
链接.js
import React from 'react';
import {Route, Link as ReactRouterLink} from 'react-router-dom';
import {createPath} from 'history';
const Link = ({to, replace, ...props}) => (
<Route path={typeof to === 'string' ? to : createPath(to)} exact>
{({match}) => (
<ReactRouterLink {...props} to={to} replace={replace || !!match} />
)}
</Route>
);
Link.propTypes = ReactRouterLink.propTypes;
Link.defaultProps = ReactRouterLink.defaultProps;
export default Link;
Run Code Online (Sandbox Code Playgroud)
应用程序.js
import Link from './link'; // use the custom Link component instead of the react-router Link
const App = () => {
<ul>
<li><Link to={{ pathname: '/one', search: 'foo=bar' }}>one</Link></li>
<li><Link to="/two">two</Link></li>
</ul>
}
Run Code Online (Sandbox Code Playgroud)
该组件使用该Route组件检查当前位置是否与to链接的 prop 定义的位置匹配。replace如果匹配,则将使用设置为 的 prop来渲染链接true。这可确保历史记录项将被替换而不是添加。
其他一切都将与正常组件一样工作Link。只需使用这个组件而不是原来的组件Link,它就会按照您想要的方式工作。
工作示例:
| 归档时间: |
|
| 查看次数: |
2252 次 |
| 最近记录: |