ReactJS,渲染后重定向

ReactJS, redirect after render

renderreturn 之后有没有办法或如何重定向?

我想要的是做这样的事情:

render() {
  return(<div>You have no access</div>)
  // then redirect to "/"

我正在考虑创建一个仅在 3 秒后在 componentDidMount 中具有重定向的组件,例如称为 <Redirect> 然后像这样使用它:

render() {
  return(<Redirect time=3> <div>You have no access</div> </Redirect>
  // then redirect to "/"

Redirect.js

componentDidMount() {
  // code for redirect using with this.props.time

还有其他方法吗?

是的,您可以实现那种重定向。

由于在路由时可以传递数据,所以可以将prevURL传递给这个组件,以代替/,实现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("/");
};

唯一剩下的就是根据代码需求将其设为通用组件,或 HOC 以供 auth 检查。


在线试用: