这是我参与8月更文挑战的第6天,活动详情查看:8月更文挑战
theme: juejin
redux 基本特性
- 整个应用只有唯一一个可信数据源,也就是只有一个 Store
- State 只能通过触发 Action 来更改
- State 的更改必须写成纯函数,也就是每次更改总是返回一个新的 State,在 Redux 里这种函数称为 Reducer
redux 数据流程
通过Action()发送请求,通过纯函数reducer对请求进行处理,返回一个新的state
Actions
Action 很简单,就是一个单纯的包含 { type, payload } 的对象type是一个常量用来标示动作类型,payload 是这个动作携带的数据。Action 需要通过 store.dispatch()方法来发送。
{
type: 'add',
text: 'Build my first Redux app'
}
reducer
纯函数,用来处理state,返回一个新的state. 绝对不要在 reducer 里面做一些引入 side-effects 的事情,比如:
- 直接修改 state 参数对象
- 请求 API
- 调用不纯的函数,比如Data.now(), Math.random() 因为 Redux 里面只有一个 Store,对应一个 State 状态,所以整个 State 对象就是由一个 reducer 函数管理,但是如果所有的状态更改逻辑都放在这一个 reducer 里面,显然会变得越来越巨大,越来越难以维护。得益于纯函数的实现,我们只需要稍微变通一下,让状态树上的每个字段都有一个 reducer 函数来管理就可以拆分成很小的 reducer 了
export const reducer = (state = 0, {type, payload = 1}) => {
switch (type) {
case 'add':
return state + payload;
case 'minus':
return state - payload;
default:
return state;
}
};
创建一个store
Hold 住整个应用的 State 状态树
- 提供一个 getState()方法获取 State
- 提供一个 dispatch() 方法发送 action 更改 State
- 提供一个 subscribe() 方法注册回调函数监听 State 的更改
export default function createStore(reduce, enhancer) {
if (enhancer) {
// enhancer 加强的意思,加强了dispatch
//执行dispatch 的时候,就是执行所有的中间件函数和store.dispatch
return enhancer(createStore)(reduce);
}
let currentState;
let currentListeners = [];
function getState(props) {
return currentState;
}
function dispatch(action) {
currentState = reduce(currentState, action);
// state 改变,执行订阅函数
currentListeners.forEach((listener) => {
listener();
});
}
//订阅和取消订阅要成对出现
function subscribe(listener) {
currentListeners.push(listener);
return () => {
const index = currentListeners.indexOf(listener);
currentListeners.splice(index, 1);
};
}
dispatch({ type: new Date().getTime() });
//默认调用一下,可以把初始值映射到redux状态管理库离
return {
getState,
dispatch,
subscribe,
};
}
总结
Redux 是 JavaScript 状态容器,提供可预测化的状态管理。