Home  >  Article  >  Web Front-end  >  What hook does react use to request data?

What hook does react use to request data?

青灯夜游
青灯夜游Original
2022-03-22 14:52:391761browse

react uses the "componentDidMount" hook to request data. React's data request is performed in the hook function componentDidMount(), which can be used to load external data or handle other side-effect codes.

What hook does react use to request data?

The operating environment of this tutorial: Windows7 system, react17.0.1 version, Dell G3 computer.

React's data request is performed in the hook function: componentDidMount

The code in the componentDidMount method is after the component has been completely mounted on the web page The call will be executed, so the data loading can be guaranteed. In addition, calling the setState method in this method will trigger re-rendering. Therefore, this method is officially designed to load external data or handle other side-effect codes.

This article summarizes several data request methods that are more convenient to use in React. There are mainly three types, are all interfaces that simulate data requests through json-server.

1 axios

This method is more commonly used and is often used in vue

Before use Download it first: npm i axios

 axios.get(' http://localhost:3000/datalist').then(res=>{
  console.log(res);
})

Result:
What hook does react use to request data?

2 fetch method

fetch is a method of HTTP data request and an alternative to XMLHttpRequest. Fetch is not a further encapsulation of ajax, but native js. The Fetch function is native js and does not use the XMLHttpRequest object. [Quoted from fetch]

fetch('http://localhost:3000/datalist').then(res=>res.json()).then(res=>{
     console.log(res)
})

Result:

What hook does react use to request data?

##3 Traditional ajax request

This should be familiar to everyone so I won’t go into details. Of course, it can also be used in react.

let xhr = new XMLHttpRequest();
xhr.addEventListener('load',handler);
xhr.open("GET",'http://localhost:3000/datalist');
xhr.send();
function handler(e){
    console.log(JSON.parse(e.currentTarget.response));
}

Result:

What hook does react use to request data?

[Related recommendations:

Redis video tutorial

The above is the detailed content of What hook does react use to request data?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn