javascript - 如何在 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;
什么是正确的方法?
解决方案
您可以在闪屏的 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。
希望能帮助到你。
推荐阅读
- c++ - HDF5 简单读取数据集失败
- javascript - 显示一定时间后如何隐藏或删除消息?
- python - 已部署 GAE NDB 安装
- javascript - Moment.js:将持续时间分割为年、月、周、日等
- javascript - d3.js:渐变填充是轮廓,如何使它变得立体?
- android - 使用 Surfaceview 尺寸调整相机视图
- google-pay - 使用 3ds 在网络上支付 Google Pay
- wordpress - WPForms:如何通过某些 Url 参数值在下拉列表中设置默认值
- javascript - NetSuite Javascript 错误:org.mozilla.javascript.Undefined@26e0a9d9
- java - 比较大型列表并提取缺失数据