How does React access API to fetch data?
In React, you can use libraries like fetch or axios to make API calls and fetch data.
Here is an example code using fetch:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// 处理获取到的数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
The example code using axios is as follows:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => {
// 处理获取到的数据
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error(error);
});
In actual development, the logic for retrieving data is often placed in React component lifecycle methods, such as componentDidMount, so that data can be immediately obtained after the component is mounted. The retrieved data can be stored in the component’s state, and then used in the render method.
for example
import React, { Component } from 'react';
import axios from 'axios';
class MyComponent extends Component {
state = {
data: null,
error: null,
};
componentDidMount() {
axios.get('https://api.example.com/data')
.then(response => {
// 更新组件状态
this.setState({ data: response.data });
})
.catch(error => {
// 更新组件状态
this.setState({ error: error.message });
});
}
render() {
const { data, error } = this.state;
if (error) {
return <div>Error: {error}</div>;
}
if (!data) {
return <div>Loading...</div>;
}
return (
<div>
{/* 使用获取到的数据渲染组件 */}
</div>
);
}
}
export default MyComponent;
In the above code, the component calls the componentDidMount method after mounting, where axios is used to make a request and store the retrieved data in the component’s state. The render method renders different content based on the component’s state.