react 路由跳转时添加加载中动画

实现思路

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);

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值