包阅导读总结
1. `Full-stack development`、`Java`、`React`、`Spring Boot`、`Todos`
2. 本文是关于全栈开发的部分内容,主要涉及使用 Java、React 和 Spring Boot 技术。重点介绍了一个 React 应用中的 `todos` 相关功能,包括初始加载、添加、切换完成状态和删除操作,还提到了 `useState` 和 `useEffect` 的使用。
3.
– 介绍了应用中 `todos` 的初始加载
– 在组件挂载时,通过 `useEffect` 从 `http://localhost:8080/todos` 获取数据并更新状态。
– 描述了添加 `todo` 的功能
– 通过 `POST` 请求向服务器添加新的 `todo` 并更新状态。
– 阐述了切换 `todo` 完成状态的操作
– 在本地更新状态,通过 `PUT` 请求同步到服务器。
– 说明了删除 `todo` 的方法
– 在本地过滤掉指定 `id` 的 `todo`,通过 `DELETE` 请求删除服务器上的数据。
– 提及了 `useState` 用于定义 `todos` 变量,以及 `Fetch API` 等相关内容。
思维导图:
文章来源:infoworld.com
作者:InfoWorld
发布时间:2024/7/24 9:00
语言:英文
总字数:1600字
预计阅读时间:7分钟
评分:87分
标签:全栈开发,Java,React,Spring Boot,CRUD 操作
以下为原文内容
本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com
import './App.css';import React, { useState, useEffect } from 'react';function App() { const [todos, setTodos] = useState([]); // Fetch todos on component mount useEffect(() => { fetch('http://localhost:8080/todos') .then(response => response.json()) .then(data => setTodos(data)) .catch(error => console.error(error)); }, []); // Function to add a new TODO item const addTodo = (description) => { fetch('http://localhost:8080/todos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ description }), }) .then(response => response.json()) .then(newTodo => setTodos([...todos, newTodo])) .catch(error => console.error(error)); }; // Toggle completion const toggleTodoComplete = (id) => { const updatedTodos = todos.map(todo => { if (todo.id === id) { return { ...todo, completed: !todo.completed }; } return todo; }); setTodos(updatedTodos); // Update completion fetch(`http://localhost:8080/todos/${id}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ completed: !todos.find(todo => todo.id === id).completed }), }) .catch(error => console.error(error)); }; const deleteTodo = (id) => { const filteredTodos = todos.filter(todo => todo.id !== id); setTodos(filteredTodos); fetch(`http://localhost:8080/todos/${id}`, { method: 'DELETE' }) .catch(error => console.error(error)); };
We have functions for creation, toggling completion, and deletion. To load the to-dos initially, we use the useEffect
effect to call the server for the initial set of to-dos when React first loads the UI. (See my introduction to React hooks to learn more about useEffect
.)
useState
lets us define the todos
variable. The Fetch API makes it pretty clean to define the back-end calls and their handlers with then
and catch
. The spread
operator also helps to keep things concise. Here’s how we set the new todos
list: