实现思路
1、首先我在路由组件componentWillReceiveProps函数中里监听路由变化,这个钩子可以监听props的变化,随之便可以每次更换路由时被触发
2、然后在路由组件里写个定时器控制动画效果
实现效果如下图。如果你想让全屏进入动画效果,那就修改一下相关元素的css浮动定位全屏就行了
实现代码如下所示,每次跳转页面都会出现加载中的效果
代码中的loading也完全可以通过redux控制,因为可能有时候我们需要等request请求结束再显示界面,当我这个项目不需要
import React, { Component } from "react";
import { Route, Switch, withRouter } from "react-router";
import { Spin } from "antd";
import Home from "../pages/Home";
import About from "../pages/About";
import Products from "../pages/Products";
import Solution from "../pages/Solution";
import SolutionDetails from "../pages/SolutionDetails";
import Download from "../pages/Download";
import Details from "../pages/Details";
import Contact from "../pages/Contact";
import ErrorPage from "../pages/Error";
class routers extends Component {
state = { loading: true };
timer = null;
/**
* 生命周期函数
*/
// 组件挂载
componentDidMount() {
this.loadingShow();
}
// 监听props变化
componentWillReceiveProps(nextProps) {
//当路由切换时
if (this.props.location !== nextProps.location) {
window.scrollTo(0, 0);
this.loadingShow();
}
}
/**
* 功能
*/
// 加载中函数
loadingShow() {
this.setState(
{
loading: true
},
() => {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
this.setState({ loading: false });
}, 1000);
}
);
}
render() {
return (
<div key={this.props.location.key}>
<Spin tip="Loading..." spinning={this.state.loading}>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/products/:id" component={Products} />
<Route exact path="/about" component={About} />
<Route exact path="/solution" component={Solution} />
<Route
exact
path="/solutionDetails/:id"
component={SolutionDetails}
/>
<Route exact path="/download" component={Download} />
<Route path="/about" component={Download} />
<Route exact path="/details/:id" component={Details} />
<Route path="/contact" component={Contact} />
<Route component={ErrorPage} />
</Switch>
</Spin>
</div>
);
}
}
export default withRouter(routers);