要点:
-
用 Context 做状态共享(UserContext + ThemeContext)
-
用
useReducer
组织状态和操作逻辑 -
异步请求模拟获取用户信息
-
自定义 Hook 提供业务层抽象
-
用
React.memo
和useCallback
防止无意义重渲染
代码示范
import React, {
createContext,
useContext,
useReducer,
useEffect,
useCallback,
memo,
} from "react";
// --- User Context ---
// 状态结构
const initialUserState = {
isLoading: false,
isAuthenticated: false,
user: null,
error: null,
};
// Action types
const USER_ACTIONS = {
LOGIN_START: "LOGIN_START",
LOGIN_SUCCESS: "LOGIN_SUCCESS",
LOGIN_FAILURE: "LOGIN_FAILURE",