首页 > 解决方案 > 重定向着陆页组件 5 秒

问题描述

在延迟 5 秒后,我正在尝试使用Redirect以下Hero React 组件。SwitchReact-Router

<Redirect to="/home" />立即将组件重定向到http://url.com/home

有关如何处理此问题的任何建议?谢谢。

class Intro extends Component {
  render() {
    return (
      <div className="d-flex w-100 h-100 mx-auto p-4 flex-column">
        <Header />
        <div 
          style={{
            paddingTop: '40px'
          }}>
        </div>
        <Hero />
        <Footer />
      </div>
    );
  }
}

export default Intro;

我也尝试过setTimeout使用

标签: reactjsreact-router

解决方案


您可以使用注入的道具historyreact-router调用. 你应该这样做:pushsetTimeoutcomponentDidMount

constructor(props) {
  // ...
  this.redirectTimeout = null;
}

componentDidMount() {
  const { history } = this.props;
  this.redirectTimeout = setTimeout(() => {
    history.push('/home')
  }, 5000);
}

编辑:确保在 5 秒结束前移出页面时清除超时以避免重定向,否则您仍将被重定向:

componentWillUnmount() {
  clearTimeout(this.redirectTimeout);
}

推荐阅读