摘要:在本教程中,您将继续将 React Todo App 与 API 服务器集成,以存储待办事项列表。
设置 API 服务器
首先,下载以下文件并将其解压缩到您的计算机上的目录中,例如 todo-api
其次,打开您的终端并导航到项目目录
cd todo-apiCode language: JavaScript (javascript)第三,运行以下 npm 命令来安装项目依赖项
npm instalCode language: JavaScript (javascript)最后,运行 npm start 命令启动 API 服务器
npm startCode language: JavaScript (javascript)API 服务器将运行并侦听端口 5000
http://:5000/Code language: JavaScript (javascript)下表显示了 API 端点
| 方法 | 端点 | 描述 | 请求正文 | 响应 |
|---|---|---|---|---|
GET | /todos | 检索所有待办事项。 | 无 | 待办事项的 JSON 数组 |
GET | /todos/:id | 通过其 ID 检索单个待办事项。 | 无 | 待办事项的 JSON 对象 |
POST | /todos | 创建新的待办事项。 | { "title": string, "completed": integer } | 已创建待办事项的 JSON 对象 |
PUT | /todos/:id | 通过其 ID 更新现有待办事项。 | { "title": string, "completed": boolean } | 已更新待办事项的 JSON 对象 |
DELETE | /todos/:id | 通过其 ID 删除待办事项。 | 无 | { "id": integer } |
将 API 集成到 React Todo App 中
要从 React 调用 API,您可以使用 Web 浏览器提供的内置 Fetch API。
显示待办事项列表
当 Todo 应用程序首次启动时,它应该调用 API 以检索所有待办事项并将它们显示在屏幕上。GET /todos
为此,我们需要
- 定义一个函数
getTodos,该函数调用 API以检索所有待办事项并更新GET/todostodos状态。 - 仅在应用程序首次启动时执行
getTodos函数。
首先,定义一个新的函数 getTodos(),该函数调用 API 并更新 todos 状态
const getTodos = async () => {
const url = 'https://:5000/todos';
try {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const storedTodos = await response.json();
// Update the state
if (storedTodos) setTodos(storedTodos);
} catch (error) {
console.error('Error during GET request:', error);
}
};Code language: JavaScript (javascript)其次,在组件首次渲染时使用 useEffect() 钩子调用 getTodos() 函数一次
useEffect(() => {
getTodos();
}, []);Code language: JavaScript (javascript)在此语法中,useEffect 是 React 中的钩子。钩子是一个函数,它为组件添加功能。
useEffect() 钩子允许您在特定时间运行函数。它接受两个参数
- 一个函数
- 一个空数组 (
[])。
空数组指示 钩子在组件首次渲染时执行函数。我们将在接下来的教程中详细介绍 React 钩子。useEffect()
创建新的待办事项
要创建新的待办事项,您需要
- 调用 API
POST /todos以在数据库中创建一个新的待办事项。 - 使用
setTodos函数将新的待办事项添加到当前待办事项状态中。
以下是 createTodo() 函数的修改版本
const createTodo = async (title) => {
// form a new todo
const newTodo = {
title: title,
completed: false,
};
// call an API to create a new todo
const url = 'https://:5000/todos';
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newTodo),
});
if (!response.ok) throw new Error('Network response was not ok');
const storedTodo = await response.json();
// set a new state
const updatedTodos = [...todos, storedTodo];
setTodos(updatedTodos);
} catch (error) {
console.error('Error creating a todo:', error);
}
};Code language: JavaScript (javascript)删除待办事项
要删除待办事项,您需要
- 调用 API
DELETE /todo/:id以删除数据库中由 ID 指定的待办事项。 - 从
todos状态中删除已删除的待办事项。
以下是 removeTodo() 函数的新版本
const removeTodo = async (id) => {
// Delete the todo
const url = `https://:5000/todos/${id}`;
try {
const response = await fetch(url, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});
if (!response.ok) throw new Error('Network response was not ok');
// Update the state
const updatedTodos = todos.filter((todo) => todo.id !== id);
setTodos(updatedTodos);
} catch (error) {
console.error('Error during DELETE request:', error);
throw error;
}
};Code language: JavaScript (javascript)更新待办事项
要更新待办事项,您需要
- 调用 API
PUT /todo/:id以更新由 id 指定的待办事项。 - 在
todos状态中更新已修改的待办事项。
以下是 changeTodo() 函数的新版本
const changeTodo = async (id, newTitle, completed = false) => {
// Update todo
const url = `https://:5000/todos/${id}`;
const data = { title: newTitle, completed };
try {
const response = await fetch(url, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
const updatedTodo = await response.json();
// Update the state
const updatedTodos = todos.map((todo) => {
if (todo.id === id) {
return { ...todo, ...updatedTodo };
}
return todo;
});
setTodos(updatedTodos);
} catch (error) {
console.error('Error during PUT request:', error);
throw error;
}
};Code language: JavaScript (javascript)Todo 应用程序的其余部分保持不变。
下载带有 API 的 React Todo App
摘要
- 使用 Web 浏览器提供的 Fetch API 调用 API。
- 使用
useEffect钩子在组件显示后运行函数一次。
本教程是否有帮助?