preface

In React, the render function returns the result, depending on the props and state of the component

We all know that the data on the UI page is not written to death, but is often retrieved from the data interface at the back end

And then populate the page with real data in which lifecycle function should the request be made? How and in what ways do YOU make Ajax requests? And how do we emulate a back-end data interface?

Then this section is what you want to know

If you want a better reading experience, you can poke the link, send Ajax requests and Mock data in React

The sample API returns the following JSON object

Suppose the back end returns a list of items like the following

{
  "goodLists": [{"id": 1, "name": "Seeds"."price": 10, "address": "Guangdong"},
      {"id": 2, name":"apple","price": 20."address":"Beijing"}, {"id": 3,"name":"orange","price": 8."address":"hunan"}, {"id": 4,"name":"peach","price: 13, ""address":"Beijing"}, {"id"5,"name":"durian","price": 18,"address":"hainan"}}]Copy the code

Name the JSON code for this list goodList. json and place it in the API folder of the root directory public

In the public directory API folder can be placed in your own simulated data, the simulated data file can only be placed in the public directory, otherwise it will report an error, does not take effect

The corresponding UI effect is shown as follows

In which lifecycle function to send the AJax request

It is also possible to place Ajax requests in the functions that the componentWillMount component is about to mount

However, the official recommendation is to place the Ajax request in the Life cycle function componentDidMount, because the DOM is already mounted by the time the life cycle is executed

Doing so takes the data returned by the Ajax request and updates the component with setState

componentDidMount(){// Make Ajax data request, axios,fetch,jquery Ajax or request}Copy the code

How do I send an AJax request?

React allows you to use your favorite Ajax libraries, such as Axios, the browser’s built-in Feach method,JQuery Ajax, or a third-party library called Request

  • The first option is to use Axios to send Ajax requests. This option is common in Vue, React and other frameworks. It supports the Promise option
NPM install -s axios or CNPM install -s axios or YARN add axiosCopy the code

After installing AXIOS, introduce the AXIos library at the top of the file that needs to use the request data, as shown below. Here is the code for the example API above

import React, { Fragment, Component } from 'react';      
import ReactDOM from 'react-dom';
import axios from 'axios'; // Introduce the AXIos library import"./style.css";


class List extends Component {
  constructor(props){
    super(props);
    this.baseUrl = '/api/goodlist'; // This. BaseUrl = // this. BaseUrl = // this'http://localhost:4000/api/goodlist'; // This. BaseUrl ='https://easy-mock.com/mock/5b24e12cf076d94c646a9aa2/api/googlists'; State = {list: []}}render(){
    const { list } = this.state;
    return (
        <Fragment>
             <ul>
                  {
                    list.map((item) => {
                      const isRed = item.price >= 10 ? 'red':' ';
                      return(< li key = {item. Id} > {item. The name} - < span the className = {isRed} > {item. Price} < / span > RMB - {item. The address} < / li >)})} < / ul > </Fragment> ); } // Ajax requests are placed within the componentDidMount lifecyclecomponentDidMountGet (this.baseurl). Then (res => {const {goodlists} = res.data; this.setState({ list: goodlists }) }) .catch(err => { console.log(err); }) } } const container = document.getElementById('root');

ReactDOM.render(<List   />, container);

Copy the code

The code above is just making an Ajax request in componentDidMount, using AXIos to request data

Once you get the data, update the component’s state data to the page using setState

At the same time, when the price is greater than 10, some logical judgment is made, so that the price is greater than 10 red, in JSX can be interpolated in the way of some special processing

Note: Json files for local simulation data (in this case goodlist.json) can only be placed in the root directory of the public directory folder, if placed elsewhere, will not work

The public directory works because the access path is the root directory. Webpack does some processing and React automatically finds the directory

  • Method 2: Use the built-in fetch method of the browser

This method is a standard browser interface that provides a simple and reasonable way to get resource data asynchronously across the network, and is becoming increasingly popular, as well as Ajax requests that are made after The componentDidMount component is mounted

componentDidMount(){fetch(){this.baseurl = this.baseurl'/api/goodlist') .then(res => res.json()) .then((result) => { console.log(result); const { goodlists } = result; this.setState({ list: {console.log(error) => {console.log(error);}, {console.log(error) => {console.log(error);  })}Copy the code

Fetch is a cutting-edge standard and a substitute for Ajax. Its API is designed based on Promise. The old version of browser does not support FETCH, so polyfill ES6-Promise is required

For more detailed fetch usage, please refer to the MDN document

  • Method 3: Use JQ Ajax

Jquery is a library that you need to install in React. Using this method to request data is not an option, but is not recommended

NPM install -s jquery or CNPM install -s jqueryCopy the code

Then, in the files where you need to request data, introduce jquery

import $ from 'jquery'
Copy the code

Then within the componentDidMount lifecycle function, use the jquer method to request data, as shown below.post,$.ajax()

componentDidMount(){
   /*
     $.get('/api/goodlist'.function(res){ console.log(res); This.setstate ({list: res.goodlists})}.bind(this))'/api/goodlist', (res) => {
       console.log(res);
       const { goodlists } = res;
       this.setState({
          list: goodlists
       })
    })
  }
Copy the code

The above is an Ajax request for data using the method provided in jquery. We only need to request one data, but we need to import the entire jquery library, which is very unreasonable under the current load on demand modular development, hence fetch and Axios solution

React recommends using AXIOS or FETCH for Ajax requests

  • Mode 4: Use the Request library:Github.com/request/req…

This is not only used in Vue,React and other frameworks, Ajax request data is also supported in wechat applet

The request module is also so popular and useful that it would feel buried if I didn’t mention it

To use it, the Request module should be installed first and then the Request-Promise module should be installed, because request-Pormise is dependent on Request, so the two dependencies must be installed in sequence

npm install -S request
npm install -S request-promise
Copy the code

Then introduce the Request-Promise library above the file where you need to use the request data and call an RP function

import rp from 'request-promise'
Copy the code

You then make Ajax data requests inside componentDidMount

componentDidMount(){// Use request-promise to request data // Take care of this. Here baseUrl does not support/API/goodlist json, the following this. BaseUrl is http://localhost:4000/api/goodlist, and real, can be Parse () const {goodlists} = rp(this.baseurl).then(res => {// This returns a string that needs to be converted to a JSON object using json.parse () const {goodlists} = JSON.parse(res); this.setState({ list: goodlists }) }) .catch(error => { console.log(error); })}Copy the code

It is also possible to use request-promise to implement Ajax data requests. Note that you cannot use native mock data when using this method

It also supports promise objects. Note that when the type that returns a successful response is a JSON string format, you need to use json.parse ()

Take a JSON string, turn it into a JSON object, and then do the processing

If you request data using AXIos, there is no formatting of the JSON sequence

summary

React requests data in several ways

  • Axios (commonly used)
  • Fetch method (early, explicit case)
  • Juery Ajax(not recommended)
  • Request (commonly used, second only to Axios)

Note: this is all put in the componentDidMount function for data requests

Mock local data in the local public directory

This method is relatively simple, directly in the project public directory to create an API folder, a new JSON file can be

When using AXIos for data requests, or fetch, the URL begins with a backslash /, as shown in the example code above, but when using request, the URL written with a backslash/does not work

Using request requires HTTP, which also supports an online interface

Add access-Control-allow-origin: * to headers for cross-domain problems

We will cover this later in the Mockoon tool

├─ API │ ├─ ├─ react-Ajax ├─ package-lock.json ├─ public // ├─ API │ ├─ API │ ├─ Goodlist. Json │ ├ ─ ─ the favicon. Ico │ ├ ─ ─ index. The HTML │ └ ─ ─ the manifest. Json ├ ─ ─ the README. Md ├ ─ ─ the SRC │ ├ ─ ─ App. Js │ ├ ─ ─ index. The js │ └ ─ ─ style.css. CSS └ ─ ─ yarn - error. The logCopy the code

Use Charles to capture localized simulation data

Charles is a proxy server, by setting itself as the network access proxy server of the system, and then intercepting requests and request results to achieve the purpose of analyzing and capturing packages, the software is written in Java, when installing Charles, first install Java environment, that is, Jdk environment Settings

Here is a look at the simple concrete use of Charles

Download this tool from Baidu Encyclopedia Charles first, and then install it next

The usage mode is as follows:

/ API/goodList will be an error if the fake data file is placed outside the project root directory public when you do not configure the Charles tool proxy service

In other words, fake data can be stored in a public directory without using Charles or other proxy tools, because React webpack automatically finds files in the public directory

Of course Charles and mockoon and other tools

Mock local data using Mockoon

To use this method, you will need to download the Mockoon tool

Official website :mockoon.com/

Use Easy Mock to fake data

Easy Mock is an open source data falsification tool from the Dasoku technology team. It is a visual and persistent service that can quickly generate simulated data

The official website :easy-mock.com

Easy-mock combines mock.js, interface proxy,Restful style, and other handy features

Replace the baseUrl in the above code with the online easy-mock

this.baseUrl = 'https://easy-mock.com/mock/5b24e12cf076d94c646a9aa2/api/googlists';
Copy the code

As for the use of more easy mock tools, you can try them out. Once you have them, you don’t need to rely on the back-end interface, so you can replace them

summary

Several ways to mock local data

  • Mock local data in the local public directory
  • Use Charles to capture localized simulation data
  • Mock local data using Mockoon
  • Using Easy-mock to mock interface data

conclusion

React generates Ajax requests with axios, Fetch,Jquery, etc. Ajax requests with Axios, Fetch,Jquery Ajax, and the way of request, where AXIos and Fetch,request is the mainstream way

At the same time, it introduces the project root directory public folder to place simulated fake data, I think this is very simple and crude, but the only disadvantage is that you have to manually write data

Using Charles and Mockoon tools to intercept local requests,mock data, requires additional configuration

Of course, easy-mock is a very useful tool for simulating backend fake data

Choose one of the above proxy data simulation methods you like. There is no good or bad tool, but you can use it well. Personally, I recommend using easy-mock, but other methods are not bad either

Then other methods are more suitable, the reason why different tools are introduced is mainly to open up their own ideas

If one tool doesn’t work, use another. There will always be one that suits you

Sometimes, will not be hanged in a tree, to believe that the method is more than difficult