Redux 基本概念

Redux 官网: https://cn.redux.js.org/
一、三大核心概念

1、Store
Store可理解为仓库、水池,用于存放数据的容器,一个应用通常只有一个Store。React / JavaScript创建Store:1
2
3import { createStore } from 'redux';
const store = createStore(reducers);Flutter / Dart创建Store。1
2
3import 'package:redux/redux.dart';
final store = Store<AppState>(reducers);
注意:不管是
React还是Flutter中,创建Store时必须要传入一个函数作为参数,该函数为Reducer,后边会讲到。
2、Action
Action在这里作名词,可理解为(向Store水池中打水漂的)石块。React / JavaScript中的action为一个JSON对象,该对象必须要有一个type属性,其他属性没有限制。1
2
3
4
5
6
7
8const add = {
type: 'ADD',
val: 5
};
const dec = {
type: 'DEC',
val: 1,
}Flutter / Dart中的action和JavaScript的用类似,但type属性不再是必须的了,这里直接使用简单的枚举来标识不同的action。1
2
3enum Actions {
ADD, DEC,
}
3、Reducer
Reducer 为不包含任何逻辑的纯函数。在向水池打水漂的例子中,水池随着石块的变化而变化遵循着某种函数规律,这个函数即为 Reducer。
Reducer 作为一个函数,接收一个状态
State和事件Action,得到新的状态NewState。React / JavaScript中的reducer。
1
2
3
4
5
6
7
8
9
10
11
12
13const reducer = (state, action) => newState;
// 以下为一个例子
const counterReducer = (state = 0, action) => {
switch (action.type) {
case 'ADD':
return state + action.val;
case 'DEC':
return state - action.val;
default:
return state;
}
}Flutter / Dart中的reducer。
1
2
3
4
5
6
7
8
9
10
11
12
13
14enum Actions {
ADD, DEC,
}
int counterReducer(int state, action) {
switch (action) {
case Actions.ADD:
return state + 1;
case Actions.DEC:
return state - 1;
default:
return state;
}
}
二、几个重要方法
1、Store 的常用方法
Store.getState()
该方法返回一个
State,在Redux中每一个State对应着的一种不同的UI状态。React / JavaScript中获取state:
1
const state = store.getState();Flutter / Dart中获取state:
1
final state = store.state;Store.dispatch(action)
可以理解为向水池
Store中扔一个石块Action。在该方法内部,Store会根据Reducer函数生成一个新的State,从而引起UI的变化。React / JavaScript中的调用 :
1
2
3
4store.dispatch({
type: 'ADD',
val: 5
});Flutter / Dart中的调用 :
1
store.dispatch(Actions.ADD);Store.subscribe(listener)
向
Store注册监听,如果Store有变化,则为回调listener。React / JavaScript中的调用 :
1
store.subscribe(() => console.log("状态变化:" + store.getState()));Flutter / Dart中的调用 :
1
store.onChange.listen(render)
2、其他常用方法
combineReducers
当业务复杂的时候,
Reducer函数肯定会需要拆分。当我们需要把多个Reducer函数进行联合的时候,就需要使用combineReducers了。React / JavaScript中的调用 :
1
2
3
4const appReducer = combineReducers({
aReducer,
bReducer,
})Flutter / Dart中的调用 :
1
2
3
4final appReducer = combineReducers(
aReducer,
bReducer,
)ActionCreator
- 为了方便创建
Action,可以统一的一个函数来创建Action。由于Flutter中的Action较为简单,不需要通过函数来创建Action,下面仅展示React中的用法。
1
2
3
4
5
6const addCteator = (value) => {
return {
type: 'ADD',
val: value,
}
};- 为了方便创建