返回
Redux的createStore实现:去伪存精,看懂它才是真的懂Redux
前端
2023-11-09 16:57:14
Redux 简介
Redux是一个流行的JavaScript状态管理库,主要用于管理应用程序的共享状态。Redux信奉“单一数据源”的原则,即应用程序的所有状态都存储在一个单一的状态树中。这种设计使得应用程序的状态更容易管理和理解。
Redux由三个核心部分组成:
- Action:Action是Redux中唯一可以改变状态树的对象。Action是一个简单的JavaScript对象,它包含一个type属性和一个payload属性。type属性指定了Action的类型,payload属性则包含了要更新的数据。
- Reducer:Reducer是一个纯函数,它接受一个Action和当前的状态树作为输入,并返回一个新的状态树。Reducer根据Action的type属性来决定如何更新状态树。
- Store:Store是Redux的核心,它负责存储应用程序的共享状态。Store包含了一个Reducer和一个getState()方法。getState()方法可以获取当前的状态树。
createStore函数
createStore函数是Redux的核心函数,它用于创建一个新的Store实例。createStore函数接受一个Reducer函数作为参数,并返回一个Store实例。
createStore函数的实现如下:
function createStore(reducer) {
if (typeof reducer !== 'function') {
throw new Error('Reducer must be a function.');
}
let state = reducer(undefined, { type: '@@redux/INIT' });
const listeners = [];
return {
getState() {
return state;
},
dispatch(action) {
if (typeof action !== 'object' || action === null) {
throw new Error('Action must be an object.');
}
state = reducer(state, action);
listeners.forEach(listener => listener());
},
subscribe(listener) {
if (typeof listener !== 'function') {
throw new Error('Listener must be a function.');
}
listeners.push(listener);
return () => {
const index = listeners.indexOf(listener);
listeners.splice(index, 1);
};
}
};
}
createStore函数的参数
createStore函数接受一个Reducer函数作为参数。Reducer函数是一个纯函数,它接受一个Action和当前的状态树作为输入,并返回一个新的状态树。Reducer函数根据Action的type属性来决定如何更新状态树。
createStore函数的返回值
createStore函数返回一个Store实例。Store实例包含了一个Reducer和一个getState()方法。getState()方法可以获取当前的状态树。
createStore函数的使用方法
createStore函数的使用方法如下:
const store = createStore(reducer);
store.dispatch({ type: 'INCREMENT_COUNTER' });
console.log(store.getState());
这段代码首先创建了一个新的Store实例,然后向Store实例派发了一个Action。Action的type属性为“INCREMENT_COUNTER”,表示要将计数器增加1。最后,输出当前的状态树。
总结
Redux的createStore函数是Redux的核心函数,它用于创建一个新的Store实例。Store实例包含了一个Reducer和一个getState()方法。getState()方法可以获取当前的状态树。createStore函数的使用方法非常简单,可以很容易地创建一个新的Store实例并向Store实例派发Action。