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

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

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

上图我打算分为两个部分来写,第一个部分就是红色的表格头,固定的内容,一个是绿色的数据表格行,把他抽成一个组件的形式来渲染数据,而这些数据呢,我打算用https://www.mockapi.io来模拟真实数据了,如果没用过mockapi的话也可以上网查一下啦。
大家也可以用我的数据接口是https://5b5e71c98e9f160014b88cc9.mockapi.io/api/v1/lists

这是我自己写的https://5e796cbb17314d0016133081.mockapi.io/reactdata
一、安装boostrap、axios

npm install bootstrap@3.3.7 --save

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

npm isntall axios --save

二、在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>
    )  
}
}

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内部添加

import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.css';
import axios from 'axios';

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.name}</td>
            <td>{user.age}</td>
            <td>{user.sex}</td>
          </tr>
      )       
      
      })
    )
  }
}
class List extends React.Component {
    constructor(props){
    super(props);
    this.state={
      users:[],
      isLoaded:false,
    }
  }
  componentDidMount(){
    const _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
      })
    })

  }

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

export default List;

转载至https://www.jianshu.com/p/309045c127c7

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容