包阅导读总结
1. `Full-stack development`、`Java`、`React`、`Spring Boot`、`Todos`
2. 本文主要介绍了使用 Java、React 和 Spring Boot 进行全栈开发的部分内容,重点展示了在 React 组件中通过 `useState`、`useEffect` 及 `Fetch API` 实现 `todos` 的加载、创建、切换完成状态和删除等功能的代码及相关解释。
3.
– 导入必要的模块
– `import ‘./App.css’;`
– `import React, { useState, useEffect } from ‘react’;`
– 定义 `App` 函数
– 使用 `useState` 定义 `todos` 状态
– 通过 `useEffect` 在组件挂载时获取 `todos` 数据
– 定义 `addTodo` 函数用于添加新的 `todo` 项
– 定义 `toggleTodoComplete` 函数切换 `todo` 项的完成状态
– 定义 `deleteTodo` 函数删除 `todo` 项
– 功能解释
– 介绍了初始加载 `todos` 的方式及相关钩子的使用
– 解释了状态管理和后端调用的实现方式
思维导图:
文章来源: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: