Redux 的核心思想是:统一状态管理 + 单向数据流 。
最核心的几个概念就是:Store → Action → Dispatch → Reducer → Store 更新 → 视图更新。
流程图:
perl
组件触发事件
↓
dispatch(action)
↓
Reducer 接收 action 修改 state
↓
Store 保存新的 state
↓
组件重新获取 state
↓
页面更新
1. Store(仓库)
Store 是 整个应用状态(state)存储中心。
可以理解成:
ini
Store = 数据仓库
里面保存所有共享状态。
例如:
css
{
count: 0,
userInfo: {
name: '张三'
}
}
创建 Store:
javascript
import { createStore } from 'redux'
import reducer from './reducer'
const store = createStore(reducer)
export default store
常用方法:
scss
store.getState() // 获取状态
store.dispatch() // 派发动作
store.subscribe() // 监听变化
2. Action(动作)
Action 描述:
"发生了什么事情"
它只是一个普通对象。
例如:
bash
{
type: 'ADD'
}
或者带参数:
bash
{
type: 'ADD',
payload: 5
}
规范:
必须有:
bash
type
通常包含:
payload
示例:
go
const addAction = {
type:'ADD',
payload:1
}
3. Dispatch(派发)
Dispatch 的作用:
把 Action 发给 Reducer
类似:
ini
dispatch = 发送命令
代码:
php
store.dispatch({
type:'ADD',
payload:1
})
执行后:
dispatch
↓
action
↓
reducer
4. Reducer(处理器)
Reducer 根据 Action 更新 State。
Reducer 必须:
- 纯函数
- 不修改原 state
- 返回新 state
格式:
perl
(state, action) => newState
示例:
javascript
const initState = {
count:0
}
function reducer(state=initState, action){
switch(action.type){
case 'ADD':
return {
...state,
count: state.count + action.payload
}
default:
return state
}
}
export default reducer
收到:
php
dispatch({
type:'ADD',
payload:1
})
state:
更新前:
css
{
count:0
}
更新后:
css
{
count:1
}
5. 完整执行流程
假设页面有按钮:
xml
<button onClick={add}>
+
</button>
点击:
第一步:触发 dispatch
php
function add(){
store.dispatch({
type:'ADD',
payload:1
})
}
第二步:Reducer 接收
收到:
bash
{
type:'ADD',
payload:1
}
执行:
kotlin
return {
count: state.count + 1
}
第三步:Store 更新
旧:
makefile
count:0
新:
makefile
count:1
第四步:React 重新渲染
组件:
javascript
const count = useSelector(
state=>state.count
)
return <h1>{count}</h1>
页面变:
0 → 1
完整链路:
scss
按钮点击
↓
dispatch(action)
↓
Reducer(state, action)
↓
return newState
↓
Store 保存
↓
React 获取最新 state
↓
页面更新
一个最小 Redux 示例
javascript
import { createStore } from 'redux'
const reducer = (state={count:0}, action)=>{
switch(action.type){
case 'ADD':
return {
count:state.count + 1
}
default:
return state
}
}
const store = createStore(reducer)
store.dispatch({
type:'ADD'
})
console.log(store.getState())
输出:
css
{
count:1
}
Redux 核心概念总结
| 概念 | 作用 | 类比 |
|---|---|---|
| Store | 保存所有状态 | 仓库 |
| State | 数据 | 商品 |
| Action | 描述做什么 | 指令 |
| Dispatch | 发送指令 | 快递员 |
| Reducer | 修改状态 | 工人 |
整体:
sql
Action
↓
Dispatch
↓
Reducer
↓
Store
↓
View 更新