[英]ReactJS, redirect after render
Is there a way or how can I redirect after some return
on render
?有没有办法或如何在
render
return
后重定向?
What I want is to do something like this:我想要的是做这样的事情:
render() {
return(<div>You have no access</div>)
// then redirect to "/"
I was thinking on create a component that only has a redirect in componentDidMount
after 3 seconds, for example called <Redirect>
then use it like this:我正在考虑创建一个在 3 秒后在 componentDidMount 中只有重定向的
componentDidMount
,例如名为<Redirect>
然后像这样使用它:
render() {
return(<Redirect time=3> <div>You have no access</div> </Redirect>
// then redirect to "/"
Redirect.js重定向.js
componentDidMount() {
// code for redirect using with this.props.time
Is there another way?还有其他方法吗?
Yes, you can achieve that kind of redirect.是的,您可以实现这种重定向。
Since you can pass data during routing, it's possible to pass the prev URL to this component, in order to replace the /
, achieving return to prev page
.由于可以在路由时传递数据,因此可以将prev URL传递给该组件,以代替
/
,实现return to prev page
。
componentDidMount() {
const intervalId = setInterval(this.timer, 1500);
this.setState({ intervalId: intervalId });
}
componentWillUnmount() {
clearInterval(this.state.intervalId);
}
timer = () => {
this.props.history.push("/");
};
The only thing left is to make it a common component, or a HOC for auth
check, based on the code demand.剩下的唯一事情就是根据代码需求使其成为通用组件或用于
auth
检查的 HOC。
Try it online:在线试一下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.