假设有一个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/