Redux 核心概念详解
Redux 核心概念详解(Action、Reducer、Store)及简单示例
1. Redux 三大核心概念
(1) Action(动作)
- 作用:描述发生了什么事件(比如"添加任务"、“删除用户”)
- 特点:
- 必须是纯对象(plain object)
- 必须有
type
属性(字符串常量) - 可以携带额外数据(通过
payload
)
// 基本action
{ type: 'ADD_TODO', payload: 'Learn Redux' }// 带更多数据的action
{type: 'ADD_USER',payload: {id: 1,name: 'Alice'}
}
(2) Reducer(归约器)
- 作用:根据action类型更新state
- 特点:
- 必须是纯函数(同样的输入必定得到同样的输出)
- 不能直接修改原state,必须返回新state
- 不能包含异步操作或副作用
// reducer基本结构
function reducer(state = initialState, action) {switch (action.type) {case 'ADD_TODO':return [...state, action.payload]case 'DELETE_TODO':return state.filter(todo => todo.id !== action.payload)default:return state}
}
(3) Store(仓库)
- 作用:管理应用状态的核心
- 职责:
- 保存整个应用的state
- 提供
getState()
获取当前状态 - 提供
dispatch(action)
触发状态更新 - 提供
subscribe(listener)
注册监听器
// 创建store
import { createStore } from 'redux'
const store = createStore(reducer)
2. 完整简单示例:计数器应用
(1) 定义Action Types
// actionTypes.js
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const RESET = 'RESET'
(2) 定义Action Creators
// actions.js
import { INCREMENT, DECREMENT, RESET } from './actionTypes'export const increment = () => ({ type: INCREMENT })
export const decrement = () => ({ type: DECREMENT })
export const reset = () => ({ type: RESET })
(3) 定义Reducer
// reducer.js
import { INCREMENT, DECREMENT, RESET } from './actionTypes'const initialState = {count: 0
}export default function counterReducer(state = initialState, action) {switch (action.type) {case INCREMENT:return { ...state, count: state.count + 1 }case DECREMENT:return { ...state, count: state.count - 1 }case RESET:return { ...state, count: 0 }default:return state}
}
(4) 创建Store
// store.js
import { createStore } from 'redux'
import counterReducer from './reducer'const store = createStore(counterReducer)export default store
(5) 在React组件中使用
// Counter.jsx
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { increment, decrement, reset } from './actions'export default function Counter() {const count = useSelector(state => state.count)const dispatch = useDispatch()return (<div><h1>Count: {count}</h1><button onClick={() => dispatch(increment())}>+</button><button onClick={() => dispatch(decrement())}>-</button><button onClick={() => dispatch(reset())}>Reset</button></div>)
}
3. 数据流图示
[用户点击按钮]
→ [dispatch(action)]
→ [Redux Store接收action]
→ [调用reducer函数]
→ [reducer返回新state]
→ [Store更新state]
→ [通知订阅者(如React组件)]
→ [组件重新渲染]
4. 关键原则总结
- 单一数据源:整个应用只有一个store
- State只读:唯一改变state的方法是触发action
- 使用纯函数修改:Reducer必须是纯函数
5. 扩展:添加中间件(如redux-thunk)
// 配置支持异步action的store
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './reducers'const store = createStore(rootReducer, applyMiddleware(thunk))
这样action creator就可以返回函数而不是对象,用于处理异步操作:
// 异步action示例
export const fetchData = () => {return async (dispatch) => {dispatch({ type: 'FETCH_START' })try {const response = await fetch('/api/data')const data = await response.json()dispatch({ type: 'FETCH_SUCCESS', payload: data })} catch (error) {dispatch({ type: 'FETCH_FAILURE', error })}}
}
这个完整示例展示了Redux的核心概念如何协同工作,从最简单的计数器到支持异步操作的完整流程。