简体   繁体   English

"如何将 React Router Link 组件的重定向延迟 1 秒?"

[英]How to delay the redirect of a React Router Link component for 1 second?

When you click a link, the browser tries to redirect the user ASAP.单击链接时,浏览器会尝试尽快重定向用户。 How can I add a 1 second delay to this process?如何在此过程中添加 1 秒延迟?

I have the following link:我有以下链接:

  <Link
    to={{
      pathname: `pathname`,
      hash: `#hash`,
    }}
    onClick={this.delayRedirect}
  >
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);

Use history to push new route after a gap of second间隔一秒后使用历史推送新路线

Here is my function component version, based on @Shishir's answer:这是我的函数组件版本,基于@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>
  );
}

Based on Pedro's answer, here's a way to add the delayAndGo function inside a component like a NavBar:根据 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, "/")}> </Link> <Link to="/about" onClick={(e) => delayAndGo(e, "/about")}> </Link> </Link> <Link to="/portfolio" onClick={(e) => delayAndGo(e, "/portfolio")}> </Link> ); }

Note the to value of the Link elements do not matter in this approach.请注意, Link元素的to值在此方法中无关紧要。

import loadable from '@loadable/component'
import pMinDelay from 'p-min-delay'

npm install p-min-delay
npm i @loadable/component

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM