让前端飞React.jsvue+js+react

React-利用axios请求数据并渲染数据

2018-07-30  本文已影响21人  我就是z
timg.jpg

本文关键词:react axios mockapi.io 等等

上篇文章快速安装create-react-app脚手架我们已经安装好了一个react项目的脚手架了,现在要用它来做点事情。就最简单的先请求接口数据,再把数据渲染出来。这就是杀鸡用牛刀了,当然我们也可以直接引入React.js也可以了~
先看下具体结构的图片

react-img-1.png
上图我打算分为两个部分来写,第一个部分就是红色的表格头,固定的内容,一个是绿色的数据表格行,把他抽成一个组件的形式来渲染数据,而这些数据呢,我打算用https://www.mockapi.io来模拟真实数据了,如果没用过mockapi的话也可以上网查一下啦。
大家也可以用我的数据接口是https://5b5e71c98e9f160014b88cc9.mockapi.io/api/v1/lists
[
  {
    "id": "1",
    "name": "小红",
    "age": 20,
    "sex": "女"
  },
  {
    "id": "2",
    "name": "小明",
    "age": 21,
    "sex": "男"
  },
  {
    "id": "3",
    "name": "翠花",
    "age": 24,
    "sex": "女"
  },
  {
    "id": "4",
    "name": "秋香",
    "age": 25,
    "sex": "女"
  },
  {
    "id": "5",
    "name": "张三",
    "age": 30,
    "sex": "男"
  }
]

现在我们开始写代码

比较懒得写样式啦,我就直接安装个boostrap,然后引入boostrap的样式好了

一、安装boostrap、axios

npm install bootstrap@3.3.7 --save

请求数据就用axios吧,也可以用JQuery的ajax(),我这里用axios

npm isntall axios --save

如果安装完成,可以看到


bs.png

二、在src目录下新建一个List.js,在List.js中:

在create-react-app可以尽情使用es6、es7的语法了,我们会对项目打包。

import React from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import axios from 'axios';

首先先把组件写好,在List.js中,我先第一个表格数据的组件TrData

//List.js
class TrData extends React.Component{
  constructor(props){
    super(props);
  }
  render(){
    return (
      this.props.users.map((user,i)=>{
          return (
              <tr key={user.id} className="text-center">
                <td>{user.id}</td>
                <td>{user.title}</td>
                <td>{user.name}</td>
                <td>{user.sex}</td>
              </tr>
          )       
      })
    )
  }
}

首先用React.Component创建一个TrData组件,然后渲染传进来的数据users,循环遍历出来.遍历users的方法是es6的map()方法,大家也可用其他方法遍历了,只要数据能出来。通过props给这个组件导入数据。接下来,我再创建一个List的组件,来显示UI视图

//List.js
class List extends React.Component {
    constructor(props){
        super(props);
  }
  render() {
      return (
        <table className="table table-bordered">
          <thead>
            <tr>
              <th className="text-center">ID</th>
              <th className="text-center">姓名</th>
              <th className="text-center">年龄</th>
              <th className="text-center">性别</th>
            </tr>
          </thead>
        <tbody>
           <TrData users={this.state.users}/>
        </tbody>
        </table>
      )  
  }
}

并且导出这个组件

//List.js
export default List;

接下来,我们来请求数据,我们知道在vue中有生命周期,可以选择在特定的生命周期上进行数据挂载。同样React也有生命周期。
当组件输出到 DOM 后会执行 componentDidMount()钩子,也就是说我们可以在componentDidMount()内请求数据,并更新数据。还有一点就是我们请求的数据要放在那儿,没错,这就是state。可能有些读者不懂这个state,这里简单讲一下,state就是可以存储组件的一系列状态。只能定义在组件内部。接下来,我两个state的两个状态,一个是users,一个是是否已经加载数据完成的isLoaded。在组件List内部加入

constructor(props){
    super(props);
    this.state={
      users:[],
      isLoaded:false
    }
  }

state需要在constructor上定义。这涉及ES6的语法特性,这里就不过多讲其他的了。我们再在List内部添加

//当组件输出到 DOM 后会执行 componentDidMount()
componentDidMount(){
    const _this=this;    //先存一下this,以防使用箭头函数this会指向我们不希望它所指向的对象。
    axios.get('https://5b5e71c98e9f160014b88cc9.mockapi.io/api/v1/lists')
    .then(function (response) {
      _this.setState({
        users:response.data,
        isLoaded:true
      });
    })
    .catch(function (error) {
      console.log(error);
      _this.setState({
        isLoaded:false,
        error:error
      })
    })
  }

通过axios请求数据,(在我之前的文章有)当请求成功后就更新state的users和isLoaded状态。更新state需要用this.setState()来更新状态,这个很类似微信小程序的setData(),state一发生改变,绑定那些状态的试图也会相应刷新改变。
我再写得合理一些,修改一下List 得render()

//List.js
render() {
      if(!this.state.isLoaded){
        return <div>Loading</div>
      }else{
      return (
        <table className="table table-bordered">
          <thead>
            <tr>
              <th className="text-center">ID</th>
              <th className="text-center">姓名</th>
              <th className="text-center">年龄</th>
              <th className="text-center">性别</th>
            </tr>
          </thead>
        <tbody>
           <TrData users={this.state.users}/>
        </tbody>
        </table>
      )  
    }
  }

当再请求数据得时候显示Loading,请求完成直接显示数据。

三、在app.js中引入List.js并渲染

//app.js
import React, { Component } from 'react';
import './App.css';
import List from './List';

class App extends Component {
  constructor(props){
    super(props);
  }
  render() {
    return (
      <div className="container">
        <List />
      </div>
    );
  }
}

export default App;

四、在create-react-app脚手架跑起来项目

npm start
res.png

这样就实现了最简单的请求数据和渲染数据了
有需要得读者可以看下源码,我把它放到github上去了https://github.com/IamZYP/List

有问题可以留言一起交流~~~
欢迎访问我的个人网站zhengyepan.com

上一篇下一篇

猜你喜欢

热点阅读