Get the App
SLTechnology News&Howtos  ›  Development  › 

How does react request data

Shulou Source: shulou.com Published: 2022-06-01 04:17:07 10月29日 Update

This article mainly introduces the relevant knowledge of "how react requests data". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "how to request data from react" can help you solve the problem.

React requests data with a "componentDidMount" hook. The data request for React is made in the hook function componentDidMount (), which can be used to load external data or to handle other side effects code.

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

The data request of React is made in the hook function: componentDidMount

The code in the componentDidMount method is not called until the component has been fully mounted on the web page, so the loading of the data is guaranteed. In addition, calling the setState method in this method triggers re-rendering. Therefore, this method is officially designed to load external data, or to deal with other side effects of code.

Several kinds of data request methods which are convenient to use in React are summarized. There are mainly the following three kinds, all of which are interfaces for simulating data requests through json-server.

1 axios

This method is commonly used, and is also often used in vue

Download npm i axios before using it.

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

Results:

2 fetch mode

Fetch is a way to request HTTP data and is an alternative to XMLHttpRequest. Fetch is not a further encapsulation of ajax, but a native js. The Fetch function is the 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)})

Results:

3 traditional ajax request

Everyone should be familiar with this, so we won't go into details. Of course, you can also use it 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));}

Results:

This is the end of the introduction to "how react requests data". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Data methods functions code methods knowledge results hooks side effects that is industry processing different practical unfamiliar traditional content official practical Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Shulou Tech Info MySQL Redmi Apple