javascript - 如何为react-router Link的onClick函数执行设置超时?

标签 javascript reactjs redux react-router timeout

假设有一个react-router Link组件。

class MyLink extends Component {
  handleOnClick = () => {
    doSomething();
    // Expecting to have a timeout before routing to another route
  };

  render() {
    return (
        <StyledLink
          to="/stock"
          onClick={this.handleOnClick}
        />
    );
  }
}

如何在 onClick 事件之后设置超时,然后再路由历史路径?

编辑

我已转发another issue具有完整的用例和解决方案。

最佳答案

这取决于您想要做什么以及 doSomething() 做什么。

如果您的 doSomething() 函数不是异步:

handleOnClick = (e) => {
    e.preventDefault(); //prevent transition
    doSomething();

    // redirect after 1 second
    window.setTimeout(() => {
       this.props.history.push(this.props.match.path);
    }, 1000)
};

如果 doSomething() 是异步,那么您可以等待它完成然后重定向:

handleOnClick = async (e) => {
    e.preventDefault(); //prevent transition
    await doSomething(); // wait until it finishes

    // redirect
    this.props.history.push(this.props.match.path);
};

或结合两者:

handleOnClick = async (e) => {
    e.preventDefault(); //prevent transition
    await doSomething(); // wait until it finishes

    // redirect 1 second after doSomething() finishes.
    window.setTimeout(() => {
       this.props.history.push(this.props.match.path);
    }, 1000)
};

如果函数是异步的,请记住处理任何错误。

this.props.match.path将获取Link的“to”属性中的路径。

另外,不要忘记在组件中使用 withRouter。

版本:

"react-router": "^4.3.1",
"react-router-dom": "^4.3.1",

关于javascript - 如何为react-router Link的onClick函数执行设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51837325/

相关文章:

javascript - 如何使用 DOM 将一行附加到 html 表?

javascript - js中如何传递变量?

reactjs - react 路由器 : 'history' is missing in type

javascript - 数组对象更新 React SetState

javascript - 将返回 promise 的函数置于 redux 状态

javascript - jQuery全屏部分向左滑动,向右滑动

javascript - 使用 MooTools 的水平 Accordion

node.js - ReactJS webapp 中的业务逻辑

javascript - <LINK> ReactJS 更改 url 但不渲染任何内容

redux - 如何在 react 管理框架中重置过滤器值?