当您单击链接时,浏览器会尝试尽快重定向用户。我怎样才能给这个过程添加 1 秒的延迟?
我有以下链接:
<Link
to={{
pathname: `pathname`,
hash: `#hash`,
}}
onClick={this.delayRedirect}
>
这是我的delayRedirect 函数的样子:
delayRedirect() {
// not sure what to put here, to delay the redirect by 1 second
}
有什么想法吗?谢谢!
import { withRouter } from 'react-router'
class Home extends Component {
delayRedirect = event => {
const { history: { push } } = this.props;
event.preventDefault();
setTimeout(()=>push(to), 1000);
}
};
<Link
to={{
pathname: `pathname`,
hash: `#hash`,
}}
onClick={this.delayRedirect}
>
}
export default withRouter(Home);
间隔一秒后使用历史记录推送新路线
这是我的函数组件版本,基于@Shishir的回答:
import React from "react";
import { Link, useHistory } from "react-router-dom";
export default function CustomLink({ to, children }) {
const history = useHistory();
function delayAndGo(e) {
e.preventDefault();
// Do something..
setTimeout(() => history.push(to), 300);
}
return (
<Link to={to} onClick={delayAndGo}>
{children}
</Link>
);
}
根据 Pedro 的回答,这里有一种在 NavBar 等组件中添加delayAndGo 函数的方法:
import React from "react";
import { Link, useHistory } from "react-router-dom";
export default function NavBar() {
const history = useHistory();
function delayAndGo(e, path) {
e.preventDefault();
// Do something..
setTimeout(() => history.push(path), 300);
}
return (
<Link to="/" onClick={(e) => delayAndGo(e, "/")}>
Home
</Link>
<Link to="/about" onClick={(e) => delayAndGo(e, "/about")}>
About
</Link>
<Link to="/portfolio" onClick={(e) => delayAndGo(e, "/portfolio")}>
Portfolio
</Link>
);
}
请注意,在此方法中,
to
元素的Link
值并不重要。
安装模块
npm install p-min-delay
npm i @loadable/component
并导入
import loadable from '@loadable/component'
import pMinDelay from 'p-min-delay'
在 useEffect 中使用 setTimeout 或事件处理程序来延迟。例如,
setTimeout(() => navigate('/new-page'), 2000);