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

Ral*_*thy 1 javascript delay hyperlink reactjs react-router

当您单击链接时,浏览器会尝试尽快重定向用户。如何在此过程中添加 1 秒延迟?

我有以下链接:

  <Link
    to={{
      pathname: `pathname`,
      hash: `#hash`,
    }}
    onClick={this.delayRedirect}
  >
Run Code Online (Sandbox Code Playgroud)

这是我的 delayRedirect 函数的样子:

  delayRedirect() {
    // not sure what to put here, to delay the redirect by 1 second
  }
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢!

Shi*_*ora 5

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);
Run Code Online (Sandbox Code Playgroud)

间隔一秒后使用历史推送新路线


Ped*_*tto 5

这是我的函数组件版本,基于 @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>
  );
}
Run Code Online (Sandbox Code Playgroud)