2016-12-11 48 views
0

我想加载加载动画到我的网站,因为它进入网站时加载相当多。它内置在ReactJS & NodeJS中,所以我需要特别了解ReactJS如何在最初进入站点时添加加载动画,以及何时在渲染新组件时有加载时间。在ReactJS中加载时加载加载动画

那么有没有办法让我的网站上的人已经,虽然它没有完全加载,所以我可以添加一个加载页面,一些CSS3动画作为加载屏幕。 问题不在于如何制作加载动画。它更多的是如何将其整合到ReactJS中。

非常感谢。

回答

0

由于ReactJS虚拟DOM速度相当快,我假设最大的加载时间是由于异步调用。您可能正在其中一个React生命周期事件中运行异步代码(例如componentWillMount)。

您的应用程序在HTTP调用所需的时间内看起来为空。要创建加载程序,您需要保持异步代码的状态。

例不使用终极版

我们将在我们的应用程序三种不同的状态:

  • REQUEST:当数据被请求但尚未加载。
  • 成功:数据成功返回。没有错误发生。
  • 失败:异步代码失败并显示错误。

当我们处于请求状态时,我们需要渲染微调器。一旦数据从服务器返回,我们将应用程序的状态更改为SUCCESS,这会触发组件重新呈现,在该呈现中我们呈现列表。使用终极版

import React from 'react' 
import axios from 'axios' 

const REQUEST = 'REQUEST' 
const SUCCESS = 'SUCCESS' 
const FAILURE = 'FAILURE' 

export default class Listings extends React.Component { 

    constructor(props) { 
    super(props) 

    this.state = {status: REQUEST, listings: []} 
    } 

    componentDidMount() { 
    axios.get('/api/listing/12345') 
     .then(function (response) { 
     this.setState({listing: response.payload, status: SUCCESS}) 
     }) 
     .catch(function (error) { 
     this.setState({listing: [], status: FAILURE}) 
     }) 
    } 

    renderSpinner() { 
     return ('Loading...') 
    } 

    renderListing(listing, idx) { 
    return (
     <div key={idx}> 
     {listing.name} 
     </div> 
    ) 
    } 

    renderListings() { 
    return this.state.listing.map(this.renderListing) 
    } 

    render() { 
    return this.state.status == REQUEST ? this.renderSpinner() : this.renderListings() 
    } 
} 

例子你几乎可以做使用终极版和Thunk中间件类似的事情。

Thunk中间件允许我们发送作为功能的动作。因此,它允许我们运行异步代码。在这里,我们正在做与上一个例子相同的事情:我们跟踪异步代码的状态。

export default function promiseMiddleware() { 
    return (next) => (action) => { 
     const {promise, type, ...rest} = action 

     if (!promise) return next(action) 

     const REQUEST = type + '_REQUEST' 
     const SUCCESS = type + '_SUCCESS' 
     const FAILURE = type + '_FAILURE' 

     next({...rest, type: REQUEST}) 

     return promise 
     .then(result => { 

      next({...rest, result, type: SUCCESS}) 

      return true 
     }) 
     .catch(error => { 
      if (DEBUG) { 
       console.error(error) 
       console.log(error.stack) 
      } 
      next({...rest, error, type: FAILURE}) 

      return false 
     }) 
    } 
} 
+0

谢谢,但我认为这不是我正在寻找的。一旦网站加载(主索引路由),页面之间的加载是毫不费力的。我想要实现的是在网站的初始连接上加载动画。我希望你明白我的意思。 – Shacrow