React Contxt詳解

React Contxt詳解

React 的 Context API 是用于跨組件層級傳遞數據的解決方案,尤其適合解決「prop drilling」(多層組件手動傳遞 props)的問題。以下是關于 Context 的詳細解析:


文章目錄

  • React Contxt詳解
      • 一、Context 核心概念
      • 二、基礎用法
        • 1. 創建 Context
        • 2. Provider 提供數據
        • 3. 在函數式組件中消費數據
      • **一、基礎用法**
        • 1. 創建 Context
        • 2. 使用 Provider 提供數據
        • 3. 在函數式組件中消費數據
      • **二、性能優化**
        • 1. 避免無效渲染
        • 2. 拆分 Context
      • **三、動態更新 Context**
        • 1. 更新 Context 的值
        • 2. 在子組件中更新 Context
      • **四、結合 useReducer 管理復雜狀態**
        • 1. 創建 Context 和 Reducer
        • 2. 在子組件中分別消費狀態和派發
      • 五、使用場景
        • 1. 主題切換(Theme) - 注釋版
        • 2. 用戶認證信息 - 注釋版
        • 3. 多語言國際化(i18n)- 注釋版
        • 4. 全局狀態管理(購物車)- 注釋版
        • 5. 復雜表單狀態 - 注釋版

一、Context 核心概念

  1. Context 對象:通過 React.createContext() 創建,包含 ProviderConsumer 兩個組件。
  2. Provider:提供數據的組件,包裹下游組件,通過 value 屬性傳遞數據。
  3. Consumer:消費數據的組件(或使用 useContext Hook),通過訂閱 Context 獲取最新值。

二、基礎用法

1. 創建 Context
import React, { createContext, useContext, useState } from 'react';// 1. 創建 Context(可選默認值)
const ThemeContext = createContext('light'); // 默認值 'light'
2. Provider 提供數據
function App() {const [theme, setTheme] = React.useState('dark');return (<ThemeContext.Provider value={{ theme, setTheme }}><Toolbar /></ThemeContext.Provider>);
}
3. 在函數式組件中消費數據
function ThemedButton() {// 使用 useContext Hook 獲取數據const { theme, setTheme } = useContext(ThemeContext);return (<buttononClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}style={{ background: theme === 'dark' ? '#333' : '#fff' }}>當前主題: {theme}</button>);
}

在 React 函數式組件中使用 Context 主要通過 useContext Hook 實現。以下是詳細步驟和示例:


一、基礎用法

1. 創建 Context
import React, { createContext, useContext, useState } from 'react';// 1. 創建 Context(可選默認值)
const ThemeContext = createContext('light'); // 默認值 'light'
2. 使用 Provider 提供數據
function App() {const [theme, setTheme] = useState('dark');return (// Provider 通過 value 傳遞數據<ThemeContext.Provider value={{ theme, setTheme }}><Toolbar /></ThemeContext.Provider>);
}
3. 在函數式組件中消費數據
function ThemedButton() {// 使用 useContext Hook 獲取數據const { theme, setTheme } = useContext(ThemeContext);return (<buttononClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}style={{ background: theme === 'dark' ? '#333' : '#fff' }}>當前主題: {theme}</button>);
}

二、性能優化

1. 避免無效渲染

如果 Providervalue 是對象,每次父組件渲染會生成新對象,導致子組件無效重渲染。使用 useMemo 優化:

function App() {const [theme, setTheme] = useState('dark');// 使用 useMemo 避免重復創建對象const value = useMemo(() => ({ theme, setTheme }), [theme]);return (<ThemeContext.Provider value={value}><Toolbar /></ThemeContext.Provider>);
}
2. 拆分 Context

將頻繁更新的數據與不常更新的數據拆分到不同的 Context 中:

// UserContext(頻繁更新)
const UserContext = createContext({ name: 'Guest' });// ThemeContext(不常更新)
const ThemeContext = createContext('light');

三、動態更新 Context

1. 更新 Context 的值

通過 useStateuseReducer 動態更新 Context:

function App() {const [theme, setTheme] = useState('dark');const toggleTheme = () => {setTheme(prev => prev === 'dark' ? 'light' : 'dark');};return (<ThemeContext.Provider value={{ theme, toggleTheme }}><Toolbar /></ThemeContext.Provider>);
}
2. 在子組件中更新 Context
function ThemeSwitcher() {const { toggleTheme } = useContext(ThemeContext);return <button onClick={toggleTheme}>切換主題</button>;
}

四、結合 useReducer 管理復雜狀態

1. 創建 Context 和 Reducer
const StateContext = createContext();
const DispatchContext = createContext();function reducer(state, action) {switch (action.type) {case 'TOGGLE_THEME':return { ...state, theme: state.theme === 'dark' ? 'light' : 'dark' };default:return state;}
}function App() {const [state, dispatch] = useReducer(reducer, { theme: 'dark' });return (<StateContext.Provider value={state}><DispatchContext.Provider value={dispatch}><Toolbar /></DispatchContext.Provider></StateContext.Provider>);
}
2. 在子組件中分別消費狀態和派發
function ThemeSwitcher() {const state = useContext(StateContext);const dispatch = useContext(DispatchContext);return (<buttononClick={() => dispatch({ type: 'TOGGLE_THEME' })}style={{ background: state.theme === 'dark' ? '#333' : '#fff' }}>當前主題: {state.theme}</button>);
}
操作代碼示例適用場景
創建 ContextcreateContext(defaultValue)定義全局狀態
提供數據<ThemeContext.Provider value>父組件向任意深度子組件傳值
消費數據useContext(ThemeContext)函數組件中直接獲取數據
動態更新value={{ theme, setTheme }}需要響應式更新的場景
性能優化useMemo 優化 Provider 的 value避免無效重渲染

五、使用場景

1. 主題切換(Theme) - 注釋版
// ThemeContext.js
import React, { createContext, useContext, useState } from 'react';// 創建主題上下文,默認值為 'light'
const ThemeContext = createContext();/*** 主題提供者組件* @param {Object} props - 組件屬性* @param {React.ReactNode} props.children - 子組件*/
export function ThemeProvider({ children }) {// 使用 useState 管理主題狀態,初始值為 'light'const [theme, setTheme] = useState('light');// 切換主題的函數const toggleTheme = () => {setTheme(prev => prev === 'light' ? 'dark' : 'light');};return (// 通過 Provider 向下傳遞主題狀態和切換函數<ThemeContext.Provider value={{ theme, toggleTheme }}>{/* 根容器動態添加主題類名 */}<div className={`app ${theme}`}>{children}</div></ThemeContext.Provider>);
}/*** 自定義主題 Hook* @returns {{theme: string, toggleTheme: function}} 主題對象*/
export const useTheme = () => {const context = useContext(ThemeContext);if (!context) {throw new Error('useTheme 必須在 ThemeProvider 內使用');}return context;
};// App.js
import { ThemeProvider } from './ThemeContext';function App() {return (// 包裹應用根組件提供主題功能<ThemeProvider><Header /><Content /></ThemeProvider>);
}// Header.js
import { useTheme } from './ThemeContext';function Header() {// 獲取當前主題狀態和切換函數const { theme, toggleTheme } = useTheme();return (<header><h1>My App</h1>{/* 主題切換按鈕 */}<button onClick={toggleTheme}>當前主題:{theme === 'light' ? '🌞 明亮' : '🌙 暗黑'}</button></header>);
}

2. 用戶認證信息 - 注釋版
// AuthContext.js
import React, { createContext, useContext, useState } from 'react';// 創建認證上下文
const AuthContext = createContext();/*** 認證提供者組件* @param {Object} props - 組件屬性* @param {React.ReactNode} props.children - 子組件*/
export function AuthProvider({ children }) {// 用戶信息狀態const [user, setUser] = useState(null);// 認證狀態const [isAuthenticated, setIsAuthenticated] = useState(false);// 登錄方法const login = (userData) => {setUser(userData);setIsAuthenticated(true);};// 退出方法const logout = () => {setUser(null);setIsAuthenticated(false);};return (<AuthContext.Provider value={{ user, isAuthenticated, login, logout }}>{children}</AuthContext.Provider>);
}/*** 自定義認證 Hook* @returns {{*   user: Object|null,*   isAuthenticated: boolean,*   login: function,*   logout: function* }} 認證上下文對象*/
export const useAuth = () => {const context = useContext(AuthContext);if (!context) {throw new Error('useAuth 必須在 AuthProvider 內使用');}return context;
};// ProtectedRoute.js
import { useAuth } from './AuthContext';
import { Navigate } from 'react-router-dom';/*** 保護路由組件* @param {Object} props - 組件屬性* @param {React.ReactNode} props.children - 子路由*/
function ProtectedRoute({ children }) {const { isAuthenticated } = useAuth();// 未認證時跳轉到登錄頁if (!isAuthenticated) {return <Navigate to="/login" replace />;}return children;
}// UserProfile.js
import { useAuth } from './AuthContext';function UserProfile() {const { user, logout } = useAuth();return (<div className="user-profile"><h2>👤 用戶資料</h2>{user ? (<><p>📛 姓名:{user.name}</p><p>📧 郵箱:{user.email}</p><p>🎭 角色:{user.role}</p></>) : (<p>?? 未獲取到用戶信息</p>)}<button onClick={logout}>🚪 退出登錄</button></div>);
}

3. 多語言國際化(i18n)- 注釋版
// I18nContext.js
import React, { createContext, useContext, useState } from 'react';// 翻譯字典配置
const translations = {en: {greeting: 'Hello',button: 'Click me',welcome: 'Welcome to our app'},zh: {greeting: '你好',button: '點擊我',welcome: '歡迎使用我們的應用'}
};// 創建國際化上下文
const I18nContext = createContext();/*** 國際化提供者組件* @param {Object} props - 組件屬性* @param {React.ReactNode} props.children - 子組件*/
export function I18nProvider({ children }) {// 當前語言狀態,默認英文const [locale, setLocale] = useState('en');/*** 翻譯函數* @param {string} key - 翻譯鍵* @returns {string} 翻譯文本*/const t = (key) => translations[locale][key] || key;return (<I18nContext.Provider value={{ locale, setLocale, t }}>{children}</I18nContext.Provider>);
}/*** 自定義國際化 Hook* @returns {{*   locale: string,*   setLocale: function,*   t: function* }} 國際化上下文對象*/
export const useI18n = () => {const context = useContext(I18nContext);if (!context) {throw new Error('useI18n 必須在 I18nProvider 內使用');}return context;
};// LanguageSwitcher.js
import { useI18n } from './I18nContext';function LanguageSwitcher() {const { locale, setLocale } = useI18n();return (<div className="language-switcher"><select value={locale} onChange={(e) => setLocale(e.target.value)}><option value="en">🇺🇸 English</option><option value="zh">🇨🇳 中文</option></select></div>);
}// Greeting.js
import { useI18n } from './I18nContext';function Greeting() {const { t } = useI18n();return (<div className="greeting"><h1>🎉 {t('welcome')}</h1><button className="cta-button">{t('button')}</button></div>);
}

4. 全局狀態管理(購物車)- 注釋版
// CartContext.js
import React, { createContext, useContext, useReducer } from 'react';// 創建購物車上下文
const CartContext = createContext();/*** 購物車 reducer 處理函數* @param {Object} state - 當前狀態* @param {Object} action - 操作對象*/
const cartReducer = (state, action) => {switch (action.type) {case 'ADD_ITEM':// 檢查是否已存在相同商品const existingItem = state.items.find(item => item.id === action.payload.id);if (existingItem) {// 數量增加return {...state,items: state.items.map(item =>item.id === action.payload.id? { ...item, quantity: item.quantity + 1 }: item)};}// 新增商品return {...state,items: [...state.items, { ...action.payload, quantity: 1 }]};case 'REMOVE_ITEM':// 過濾移除商品return {...state,items: state.items.filter(item => item.id !== action.payload.id)};case 'CLEAR_CART':// 清空購物車return { ...state, items: [] };default:return state;}
};/*** 購物車提供者組件* @param {Object} props - 組件屬性* @param {React.ReactNode} props.children - 子組件*/
export function CartProvider({ children }) {// 使用 useReducer 管理復雜狀態const [cart, dispatch] = useReducer(cartReducer, { items: [] });// 添加商品到購物車const addToCart = (product) => {dispatch({ type: 'ADD_ITEM', payload: product });};// 從購物車移除商品const removeFromCart = (productId) => {dispatch({ type: 'REMOVE_ITEM', payload: { id: productId } });};// 清空購物車const clearCart = () => {dispatch({ type: 'CLEAR_CART' });};// 計算總數量const totalItems = cart.items.reduce((sum, item) => sum + item.quantity, 0);// 計算總金額const totalPrice = cart.items.reduce((sum, item) => sum + (item.price * item.quantity), 0);return (<CartContext.Provider value={{ cart, addToCart, removeFromCart, clearCart,totalItems,totalPrice}}>{children}</CartContext.Provider>);
}/*** 自定義購物車 Hook* @returns {{*   cart: Object,*   addToCart: function,*   removeFromCart: function,*   clearCart: function,*   totalItems: number,*   totalPrice: number* }} 購物車上下文對象*/
export const useCart = () => {const context = useContext(CartContext);if (!context) {throw new Error('useCart 必須在 CartProvider 內使用');}return context;
};// ProductItem.js
import { useCart } from './CartContext';function ProductItem({ product }) {const { addToCart } = useCart();return (<div className="product-card"><h3>{product.name}</h3><p>💰 價格:${product.price}</p><button onClick={() => addToCart(product)}className="add-to-cart">🛒 加入購物車</button></div>);
}// CartSummary.js
import { useCart } from './CartContext';function CartSummary() {const { cart, removeFromCart, clearCart, totalItems, totalPrice } = useCart();return (<div className="cart-summary"><h2>🛍? 購物車({totalItems} 件商品)</h2><ul className="cart-items">{cart.items.map(item => (<li key={item.id} className="cart-item"><span>{item.name} × {item.quantity}</span><span>${item.price * item.quantity}</span><button onClick={() => removeFromCart(item.id)}className="remove-button">? 移除</button></li>))}</ul><div className="cart-total"><p>💵 總計:${totalPrice}</p><button onClick={clearCart}className="clear-button">🧹 清空購物車</button></div></div>);
}

5. 復雜表單狀態 - 注釋版
// FormContext.js
import React, { createContext, useContext, useState } from 'react';// 創建表單上下文
const FormContext = createContext();/*** 表單提供者組件* @param {Object} props - 組件屬性* @param {React.ReactNode} props.children - 子組件*/
export function FormProvider({ children }) {// 管理復雜表單數據結構const [formData, setFormData] = useState({personalInfo: {firstName: '',lastName: '',email: ''},address: {street: '',city: '',zipCode: ''},preferences: {newsletter: false,notifications: true}});/*** 更新表單字段* @param {string} section - 表單區塊(personalInfo/address/preferences)* @param {string} field - 字段名稱* @param {any} value - 字段值*/const updateField = (section, field, value) => {setFormData(prev => ({...prev,[section]: {...prev[section],[field]: value}}));};// 表單驗證方法const validateForm = () => {// 示例驗證邏輯const isValid = !!(formData.personalInfo.firstName &&formData.personalInfo.email.includes('@'));return isValid;};return (<FormContext.Provider value={{ formData, updateField, validateForm }}>{children}</FormContext.Provider>);
}/*** 自定義表單 Hook* @returns {{*   formData: Object,*   updateField: function,*   validateForm: function* }} 表單上下文對象*/
export const useForm = () => {const context = useContext(FormContext);if (!context) {throw new Error('useForm 必須在 FormProvider 內使用');}return context;
};// PersonalInfoStep.js
import { useForm } from './FormContext';function PersonalInfoStep() {const { formData, updateField } = useForm();return (<div className="form-section"><h2>📝 個人信息</h2><div className="form-group"><label>名字:</label><inputtype="text"value={formData.personalInfo.firstName}onChange={(e) => updateField('personalInfo', 'firstName', e.target.value)}placeholder="請輸入名字"/></div><div className="form-group"><label>姓氏:</label><inputtype="text"value={formData.personalInfo.lastName}onChange={(e) => updateField('personalInfo', 'lastName', e.target.value)}placeholder="請輸入姓氏"/></div><div className="form-group"><label>郵箱:</label><inputtype="email"value={formData.personalInfo.email}onChange={(e) => updateField('personalInfo', 'email', e.target.value)}placeholder="example@domain.com"/></div></div>);
}// FormSubmit.js
import { useForm } from './FormContext';function FormSubmit() {const { formData, validateForm } = useForm();const handleSubmit = () => {if (validateForm()) {console.log('? 表單驗證通過,提交數據:', formData);// 這里可以添加實際的提交邏輯alert('表單提交成功!');} else {console.log('? 表單驗證失敗');alert('請填寫必填字段!');}};return (<button onClick={handleSubmit}className="submit-button">提交表單</button>);
}</div><div className="form-group"><label>郵箱:</label><inputtype="email"value={formData.personalInfo.email}onChange={(e) => updateField('personalInfo', 'email', e.target.value)}placeholder="example@domain.com"/></div></div>);
}// FormSubmit.js
import { useForm } from './FormContext';function FormSubmit() {const { formData, validateForm } = useForm();const handleSubmit = () => {if (validateForm()) {console.log('? 表單驗證通過,提交數據:', formData);// 這里可以添加實際的提交邏輯alert('表單提交成功!');} else {console.log('? 表單驗證失敗');alert('請填寫必填字段!');}};return (<button onClick={handleSubmit}className="submit-button">提交表單</button>);
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/906337.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/906337.shtml
英文地址,請注明出處:http://en.pswp.cn/news/906337.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

使用 lock4j-redis-template-spring-boot-starter 實現 Redis 分布式鎖

在分布式系統中&#xff0c;多個服務實例可能同時訪問和修改共享資源&#xff0c;從而導致數據不一致的問題。為了解決這個問題&#xff0c;分布式鎖成為了關鍵技術之一。本文將介紹如何使用 lock4j-redis-template-spring-boot-starter 來實現 Redis 分布式鎖&#xff0c;從而…

Vue響應式系統演進與實現解析

一、Vue 2 響應式實現詳解 1. 核心代碼實現 // 依賴收集器&#xff08;觀察者模式&#xff09; class Dep {constructor() {this.subscribers new Set();}depend() {if (activeEffect) {this.subscribers.add(activeEffect);}}notify() {this.subscribers.forEach(effect &g…

Mujoco 學習系列(一)安裝與部署

這個系列文章用來記錄 Google DeepMind 發布的 Mujoco 仿真平臺的使用過程&#xff0c;Mujoco 是具身智能領域中非常知名的仿真平臺&#xff0c;以簡單易用的API和精準的物理引擎而著稱&#xff08;PS&#xff1a;原來Google能寫好API文檔啊&#xff09;&#xff0c;也是我平時…

Ai學習之openai api

一、什么是openai api 大家對特斯拉的馬斯克應該是不陌生的&#xff0c;openai 就是馬斯克投資的一家研究人工智能的公司&#xff0c;它就致力于推動人工智能技術的發展&#xff0c;目標是確保人工智能對人類有益&#xff0c;并實現安全且通用的人工智能。 此后&#xff0c;O…

leetcode 合并區間 java

用 ArrayList<int[]> merged new ArrayList<>();來定義數組的list將數組進行排序 Arrays.sort(intervals,(a,b) -> Integer.compare(a[0],b[0]));如果前面的末尾>后面的初始&#xff0c;那么新的currentInterval的末尾這兩個數組末尾的最大值&#xff0c;即…

std::vector<>.emplace_back

emplace_back() 詳解&#xff1a;C 就地構造的效率革命 emplace_back() 是 C11 引入的容器成員函數&#xff0c;用于在容器尾部就地構造&#xff08;而非拷貝或移動&#xff09;元素。這一特性顯著提升了復雜對象的插入效率&#xff0c;尤其適用于構造代價較高的類型。 一、核…

Dify實戰案例《AI面試官》更新,支持語音交互+智能知識庫+隨機題庫+敏感詞過濾等...

大模型應用課又更新了&#xff0c;除了之前已經完結的兩門課&#xff08;視頻圖文&#xff09;&#xff1a; 《Spring AI 從入門到精通》《LangChain4j 從入門到精通》 還有目前正在更新的 《Dify 從入門到實戰》 本周也迎來了一大波內容更新&#xff0c;其中就包括今天要介紹…

AGI大模型(29):LangChain Model模型

1 LangChain支持的模型有三大類 大語言模型(LLM) ,也叫Text Model,這些模型將文本字符串作為輸入,并返回文本字符串作為輸出。聊天模型(Chat Model),主要代表Open AI的ChatGPT系列模型。這些模型通常由語言模型支持,但它們的API更加結構化。具體來說,這些模型將聊天消…

動態IP技術在跨境電商中的創新應用與戰略價值解析

在全球化4.0時代&#xff0c;跨境電商正經歷從"流量紅利"向"技術紅利"的深度轉型。動態IP技術作為網絡基礎設施的關鍵組件&#xff0c;正在重塑跨境貿易的運營邏輯。本文將從技術架構、應用場景、創新實踐三個維度&#xff0c;揭示動態IP如何成為跨境電商突…

android雙屏之副屏待機顯示圖片

摘要&#xff1a;android原生有雙屏的機制&#xff0c;但需要芯片廠商適配框架后在底層實現。本文在基于芯發8766已實現底層適配的基礎上&#xff0c;僅針對上層Launcher部分對系統進行改造&#xff0c;從而實現在開機后副屏顯示一張待機圖片。 副屏布局 由于僅顯示一張圖片&…

STM32之中斷

一、提高程序實時性的架構方案 輪詢式 指的是在程序運行時&#xff0c;首先對所有的硬件進行初始化&#xff0c;然后在主程序中寫一個死循環&#xff0c;需要運行的功能按照順序進行執行&#xff0c;輪詢系統是一種簡單可靠的方式&#xff0c;一般適用于在只需要按照順序執行…

LLM應用開發平臺資料

課程和代碼資料 放下面了&#xff0c;自取&#xff1a; https://pan.quark.cn/s/57a9d22d61e9

硬盤健康檢測與性能測試的實踐指南

在日常使用 Windows 系統的過程中&#xff0c;我們常常需要借助各種工具來優化性能、排查問題或管理文件。針對windows工具箱進行實測解析&#xff0c;發現它整合了多種實用功能&#xff0c;能夠幫助用戶更高效地管理計算機。 以下為測試發現的功能特性&#xff1a; 硬件信息查…

正則表達式進階(三):遞歸模式與條件匹配的藝術

在正則表達式的高級應用中&#xff0c;遞歸模式和條件匹配是處理復雜嵌套結構和動態模式的利器。它們突破了傳統正則表達式的線性匹配局限&#xff0c;能夠應對嵌套括號、HTML標簽、上下文依賴等復雜場景。本文將詳細介紹遞歸模式&#xff08;(?>...)、 (?R) 等&#xff0…

從零開始創建React項目及制作頁面

一、React 介紹 React 是一個由 Meta&#xff08;原Facebook&#xff09; 開發和維護的 開源JavaScript庫&#xff0c;主要用于構建用戶界面&#xff08;User Interface, UI&#xff09;。它是前端開發中最流行的工具之一&#xff0c;廣泛應用于單頁應用程序&#xff08;SPA&a…

【前端部署】通過 Nginx 讓局域網用戶訪問你的純前端應用

在日常前端開發中&#xff0c;我們常常需要快速將本地的應用展示給局域網內的同事或測試人員&#xff0c;而傳統的共享方式往往效率不高。本文將指導你輕松地將你的純前端應用&#xff08;無論是 Vue, React, Angular 或原生項目&#xff09;部署到本地&#xff0c;并配置局域網…

【Python裝飾器深潛】從語法糖到元編程的藝術

目錄 ?? 前言??? 技術背景與價值?? 當前技術痛點??? 解決方案概述?? 目標讀者說明?? 一、技術原理剖析?? 核心概念圖解?? 核心作用講解?? 關鍵技術模塊說明?? 技術選型對比??? 二、實戰演示?? 環境配置要求?? 核心代碼實現案例1:基礎計時裝飾器案…

mbed驅動st7789屏幕-硬件選擇及連接(1)

目錄 1.整體介紹 2. 硬件選擇 2.1 mbed L432KC 2.2 ST7789 240*240 1.3寸 3. mbed與st7789的硬件連接 4. 總結 1.整體介紹 我們在使用單片機做一些項目的時候,交互性是最重要的因素。那么對于使用者而言,交互最直接的體現無非就是視覺感知,那么我們希望將項目通過視覺…

SpringBoot集成Jasypt對數據庫連接密碼進行加密、解密

引入依賴 <!--配置密碼加密--><dependency><groupId>com.github.ulisesbocchio</groupId><artifactId>jasypt-spring-boot-starter</artifactId><version>3.0.3</version></dependency><plugin><groupId>c…

分類器引導的條件生成模型

分類器引導的條件生成模型 分類器引導的條件生成模型1. **基本概念**2. **核心思想**3. **實現步驟&#xff08;以擴散模型為例&#xff09;**4. **優點**5. **挑戰與注意事項**6. **應用場景**7. **數學推導**總結 分類器引導的條件生成模型 分類器引導的條件生成模型是一種通…