-
Notifications
You must be signed in to change notification settings - Fork 54
Open
Labels
Description
store
store 是什么
store是一个管理state的大对象,并且提供了一系列的方法
getState(), //返回state
dispatch(action), // 派发一个action
subscribe() //订阅监听
通过redux 提供的 createStore,传入reducer函数,我们可以得到一个store对象
import { createStore } from 'redux'
const store = createStore(reducer)
简单实现一个createstore函数
//这是一个工厂函数,可以创建store
const createStore = (reducer) => {
let state; // 定义存储的state
let listeners = [];
// getState的作用很简单就是返回当前是state
const getState = ()=> state;
//定义一个派发函数
//当在外界调用此函数的时候,会修改状态
const dispatch = (action)=>{
//调用reducer函数修改状态,返回一新的状态并赋值给这个局部状态变量
state = reducer(state,action);
//依次调用监听函数,通知所有的监听函数
listeners.forEach(listener => listener());
}
//订阅此状态的函数,当状态发生变化的时候记得调用此监听函数
const subscribe = function(listener){
//先把此监听 加到数组中
listeners.push(listener);
//返回一个函数,当调用它的时候将此监听函数从监听数组移除
return function(){
listeners = listeners.filter(l => l != listener);
}
}
//默认调用一次dispatch给state赋一个初始值
dispatch({types: 'INIT'});
return {
getState,
dispatch,
subscribe
}
}
使用
function numReducer (state = 0, action) {
switch (action.types) {
case 'increase':
return state + 1
break;
case 'deincrease':
return state - 1
default:
return state
}
}
let store = createStore(numReducer);
store.subscribe(() => {
console.log('触发了')
})
store.dispatch({types: 'increase'})
console.log(store.getState())
// 触发了 1
注意的点
根据官方的说法,一个应用应该只有一个store,即单一数据源,我们通过合并reducer 来壮大state tree
未完