状态管理是前端应用架构中的核心概念,指的是管理应用中所有可变数据和状态变化的方式。随着应用复杂度增加,组件间共享状态变得越来越困难,需要专门的解决方案来统一管理状态。
// 创建 Context
const ThemeContext = React.createContext()
// 提供者
function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light')
return (
<ThemeContext.Provider value=>
{children}
</ThemeContext.Provider>
)
}
// 消费者
function Component() {
const { theme, setTheme } = useContext(ThemeContext)
return (
<button onClick={() => setTheme('dark')}>
当前主题: {theme}
</button>
)
}
// Action
const increment = () => ({ type: 'INCREMENT' })
// Reducer
function counterReducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1
default:
return state
}
}
// Store
const store = createStore(counterReducer)
// Dispatch
store.dispatch(increment())
import { create } from 'zustand'
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 }))
}))
// 在组件中使用
function Counter() {
const { count, increment } = useStore()
return <button onClick={increment}>{count}</button>
}
import { useQuery } from 'react-query'
function FetchData() {
const { data, error, isLoading } = useQuery('todos', fetchTodos)
if (isLoading) return 'Loading...'
if (error) return 'Error!'
return (
<ul>
{data.map(todo => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
)
}
存储应用状态的地方
描述状态变化的意图
根据 Action 更新状态的纯函数
在 Action 和 Reducer 之间处理副作用
从 Store 中选择特定数据
状态不可直接修改,通过拷贝更新