Axios npm如何与React.js结合使用?
{user ? (
) : (
);
};
export default UserInfo;
```
4. 处理响应数据
在上述示例中,当 Axios 请求成功时,会将获取到的用户信息存储到组件的状态中,并更新 UI。如果请求失败,会在控制台输出错误信息。
四、案例分析
以下是一个使用 Axios 与 React.js 实现的案例:一个简单的待办事项列表应用。
1. 创建项目
首先,创建一个 React.js 项目:
```bash
npx create-react-app todo-list
cd todo-list
```
2. 安装 Axios
在项目中安装 Axios 库:
```bash
npm install axios
```
3. 创建组件
创建一个名为 `TodoList` 的组件,用于展示待办事项列表:
```javascript
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const TodoList = () => {
const [todos, setTodos] = useState([]);
useEffect(() => {
axios.get('/todos')
.then(response => {
setTodos(response.data);
})
.catch(error => {
console.error('Error fetching todos:', error);
});
}, []);
return (
User Info
Name: {user.name}
Email: {user.email}
Loading...
)}-
{todos.map(todo => (
- {todo.title} ))}
猜你喜欢:全链路监控