Home > Article > Web Front-end > What hook does react use to request data?
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.
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:
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:
##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: [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!