骨架屏react_在React js中创建动画骨架加载器

骨架屏react

In this tutorial, I’ll show you how to create an animated skeleton loader for your React application. Skeleton loaders are perfect for your React application rather than that of traditional loaders because they are focused on the view. Youtube, medium, Linkedin, etc all are using skeleton screens to load the data. So let’s get started on how to implement that on your React application.

在本教程中,我将向您展示如何为React应用程序创建动画骨架加载器。 骨架加载器非常适合您的React应用程序,而不是传统加载器,因为它们专注于视图。 Youtube,Medium,Linkedin等都在使用骨架屏幕来加载数据。 因此,让我们开始如何在React应用程序上实现它。

要求 (Requirements)

  1. Open your project directory and install axios and react-loading-skeleton.

    打开项目目录,然后安装axios和react-loading-skeleton。
npm i axios react-loading-skeleton --save

2. Now open your app.js file and import axios to fetch users data from jsonplaceholder.

2.现在打开您的app.js文件并导入axios以从jsonplaceholder获取用户数据。

import React, { Component } from 'react'
import axios from 'axios'


export default class App extends Component {
  async getUsersData(){
    const res = await axios.get('http://jsonplaceholder.typicode.com/users')
    console.log(res.data)
  }
  componentDidMount(){
    this.getUsersData()
  }
  render() {
    return (
      <div>
        
      </div>
    )
  }
}

Here we have created getUserData method to fetch data and then passed that method into componentDidMount lifecycle method.

Here we have created getUserData method to fetch data and then passed that method into componentDidMount lifecycle method.

3. Now I will create a simple UI for demonstration purposes. Paste the below code in your App.js and App.css file.

3.现在,我将创建一个简单的UI进行演示。 将以下代码粘贴到您的App.jsApp.css文件中。

import React, { Component } from 'react'
import axios from 'axios'
import './App.css'


export default class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      users: [],
    }
  }
  async getUsersData(){
    const res = await axios.get('http://jsonplaceholder.typicode.com/users')
    const users = res.data.slice(0, 4)
    this.setState({users})
  }
  componentDidMount(){
    this.getUsersData()
  }
  render() {
    const {users} = this.state
    return (
      <div className="usercard">
        {users.map(u => 
    <div key={u.id} className="cards">
      <h3>{u.name}</h3>
    <p>{u.username}</p>
    <p><a href={`mailto:${u.email}`}>{u.email}</a></p>
    <p><a href={u.website}>{u.website}</a></p>
    <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis id eaque delectus quis. Voluptatum cum minus nemo aliquam, necessitatibus accusantium quia maxime ab nesciunt! Sapiente voluptatibus vero nobis autem quasi.</p>
    </div>)}
      </div>
    )
  }
}
body {
  background: #e2e1e0;


}
.usercard{
  padding: 20px;
  
}


.cards{
  box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
  background: #fff;
  padding: 10px;
  margin: 10px;
}

So what we exactly doing here? We are first slicing our data using the javascript slice method to load only 4 user data. After that, we are using the Javascript map function to iterate our array. It will now look something similar to this.

那我们到底在做什么? 我们首先使用javascript slice方法对数据进行切片,以仅加载4个用户数据。 之后,我们使用Javascript 映射函数来迭代数组。 现在看起来与此类似。

Image for post

4. Now we have to make sure that while data is getting fetched from the API there is some statement. For that, we will first initialize the loading state as true in our constructor and after the response, we will change the loading state to false using the setState method. After that, we will use the javascript if-else statement to check that while data is getting fetched from the API the user will see the animated skeleton loader. Below is the updated App.js code.

4.现在,我们必须确保从API获取数据时有一些语句。 为此,我们将首先在构造函数中将加载状态初始化为true ,然后在响应之后,使用setState方法将加载状态更改为false 。 之后,我们将使用javascript if-else语句来检查从API获取数据时,用户将看到动画骨架加载器。 下面是更新的App.js代码。

import React, { Component } from 'react'
import axios from 'axios'
import './App.css'
import Skeleton from 'react-loading-skeleton'


export default class App extends Component {
  constructor(props){
    super(props)
    this.state = {
      users: [],
      loading: true
    }
  }
  async getUsersData(){
    /* With Timeout */
    return await setTimeout(async () => {
      const res = await axios.get('http://jsonplaceholder.typicode.com/users')
      const users = res.data.slice(0, 4)
    this.setState({users, loading:false})
    }, 5000)




    /* Without Timeout (Comment out if you don't want to use setTimeout) */
    // const res = await axios.get('http://jsonplaceholder.typicode.com/users')
    // const users = res.data.slice(0, 4)
    // this.setState({users, loading:false}) 


  }
  componentDidMount(){
    this.getUsersData()
  }
  render() {
    const {users} = this.state


    if(this.state.loading){
      return (<><div className="usercard"><div className="cards">
        <Skeleton height={20} count={4}/>  <Skeleton height={100}/>
        </div></div><div className="usercard"><div className="cards">
        <Skeleton count={4}/> <Skeleton height={100}/>
        </div></div><div className="usercard"><div className="cards">
        <Skeleton count={4}/> <Skeleton height={100}/>
        </div></div><div className="usercard"><div className="cards">
        <Skeleton count={4}/> <Skeleton height={100}/>
        </div></div></>)
    }
    return (
      <div className="usercard">
        { users.map(u => 
    <div key={u.id} className="cards">
      <h3>{u.name}</h3>
    <p>{u.username}</p>
    <p><a href={`mailto:${u.email}`}>{ u.email}</a></p>
    <p><a href={u.website}>{u.website}</a></p>
    <p>Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nobis id eaque delectus quis. Voluptatum cum minus nemo aliquam, necessitatibus accusantium quia maxime ab nesciunt! Sapiente voluptatibus vero nobis autem quasi.</p>
    </div>)}
      </div>
    )
  }
}

Note: we have used the javascript setTimeout method to get the response after 3 sec so that loader can be seen as the response from the API is too fast for the loader to be seen. There is also code without setTimeout just remove comment to use.

Note: we have used the javascript setTimeout method to get the response after 3 sec so that loader can be seen as the response from the API is too fast for the loader to be seen. There is also code without setTimeout just remove comment to use.

Here is the final output

这是最终的输出

Image for post

A live example and git repository are down below for your reference.

下面提供了一个实时示例和git存储库供您参考。

翻译自: https://medium.com/how-to-react/create-an-animated-skeleton-loader-in-react-js-6d1c28e0adc7

骨架屏react

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值