首页 > 解决方案 > 如何在 React 中 n 秒后以编程方式滑动(使用转换)到另一条路线?

问题描述

我正在尝试构建一个移动优先 web 应用程序,它需要我显示一个启动页面几秒钟,然后使用幻灯片效果自动转换到登录页面。这应该只发生在启动页面上。

我不想在登录页面本身上创建覆盖,因为我希望能够在启动页面上执行一些我希望独立于其他页面的操作。

我想做的另一件事是防止用户再次看到启动页面,如果他们尝试手动导航到它,但我认为我可以使用身份验证 HOC 来处理它,但现在路由转换效果更重要。

我一直在研究 React CSS 过渡,但我很困惑,没有找到任何可以满足我的目的的东西。

这是我的代码:

应用程序.js

import React from 'react';
import {
  Route,
  Switch
} from 'react-router-dom';
import { ConnectedRouter } from 'connected-react-router'

import Home from './homeComponent';
import Login from './loginComponent';

const App = ({ history }) => {
  return (
    <ConnectedRouter history={history}>
        <Switch>
          <Route exact={true} path="/" component={Home} />
          <Route path="/login" component={Login} />
        </Switch>
    </ConnectedRouter>
  );
};

export default App;

homeComponent.js

import React, { Component } from 'react';

class HomeComponent extends Component {
  render() {
    return (
      <div>
        <div className="row">
          <div className="col-md-12"><h1>Home</h1></div>
        </div>
      </div>
    );
  }
}

export default HomeComponent;

登录组件.js

import React, { Component } from 'react';

class LoginComponent extends Component {
  render() {
    return (
      <div>
        <div className="row">
          <div className="col-md-12"><h1>Login</h1></div>
        </div>
      </div>
    );
  }
}

export default LoginComponent;

什么是正确的方法?

标签: javascriptreactjsreact-router

解决方案


您可以在闪屏的 componentDidMount 生命周期钩子上设置超时以更改到登录页面的路由

import React, { Component } from 'react';

class HomeComponent extends Component {

  componentDidMount() {
    setTimeout(() => {
      this.props.history.push('/login')

      /* here you could run a function passed by the main container in the props
         where you can change the state of the parent component to mark the splash
         screen as showed, and redirect directly to the login page or the page after 
         that if already logged */

    }, 5000 /* or the time you want in miliseconds */)
  }

  render() {
    return (
      <div>
        <div className="row">
          <div className="col-md-12"><h1>Home</h1></div>
        </div>
      </div>
    );
  }
}

export default HomeComponent;

this.props.history.push('/login') 是 react-router 提供的 action creator。

希望能帮助到你。


推荐阅读