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

时间:2018-08-11 21:09:34

标签: javascript reactjs hyperlink react-router delay

单击链接时,浏览器将尝试尽快重定向用户。如何在此过程中添加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
  }

有什么想法吗?谢谢!

2 个答案:

答案 0 :(得分:3)

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);

使用历史记录在间隔一秒钟后推新路线

答案 1 :(得分:1)

这是我的功能组件版本,基于@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>
  );
}