When the front end is developed separately, in order for the front end to simulate the background data, we need to “make the data” ourselves, hence mock.js

// The image is from the Internet

Steps to use MockJS

  1. Install mockjs, yarn add Mockjs/NPM install mockjs
  2. Custom data format, view configuration

For example, I create mockData.js in the SRC/mockData directory

import Mock from 'mockjs';
// A configuration is made to write more urls
const urlObj = {
  indexURL: '/'.bookURL: '/book'
};

Mock. Mock (url,options) returns a promise object. Mock (url,options) returns a promise object
Mock.mock(urlObj.indexURL, {
  'list|8': [{'id|+1': 1.name: '@cname'.'age|18-100': 23,}]});// This configuration will be hit when '/book' is requested
Mock.mock(urlObj.bookURL, {
  'book|8': [{'id|+1': 1.'bookName': '@cname'.'publishDate': '@date("yyyy-MM-dd")',}]});Copy the code
  1. Get the data. I’m using Axios here in react

I get the data in app under SRC

import React, { Component, Fragment } from 'react';
import axios from 'axios';
// Be sure to introduce mock matching files to simulate request data
import './mockdata/mockdata';

import './css/app.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      indexData: [].bookData:[]
    };
  }

  async componentDidMount() {
  	// Request data and rename the returned result data to indexData and bookData
    const { data: indexData } = await axios.get('/');
    const { data: bookData } = await axios.get('/book');
    this.setState({
      indexData: indexData.list,
      bookData: bookData.book,
    });
  }

  render() {
    return (
      <Fragment>// Render the personal list<table>
          <caption>Personal Information Sheet</caption>
          <thead>
            <tr>
              <th>PERSON_ID</th>
              <th>The name</th>
              <th>age</th>
            </tr>
          </thead>

          <tbody>
            {this.state.indexData.map((item) => (
              <tr key={item && item.id} >
                <td>{item && item.id}</td>
                <td>{item && item.name}</td>
                <td>{item && item.age}</td>
              </tr>
            ))}
          </tbody>
        </table>// Render a single linked list of books<table>
          <caption>A single book</caption>
          <thead>
            <tr>
              <th>BOOK_ID</th>
              <th>Title:</th>
              <th>Publication date</th>
            </tr>
          </thead>

          <tbody>
            {this.state.bookData.map((item) => (
              <tr key={item && item.id} >
                <td>{item && item.id}</td>
                <td>{item && item.author}</td>
                <td>{item && item.publishDate}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Fragment>); }}export default App;

Copy the code