import { createStore } from 'redux' const initState = { count:0 } const ADD_TODO = { type:'ADD', payload:'加法操做' } const LESS_TODO = { type:'LESS', payload:'减法操做' } const counter = (state = initState,action) => { switch(action.type){ case 'ADD': return { count:state.count+1 } case 'LESS': return { count:state.count-1 } default: return state; } } let store = createStore(counter); let unlistener = store.subscribe(()=>{ console.log(store.getState()) }) store.dispatch(ADD_TODO); store.dispatch(ADD_TODO); store.dispatch(ADD_TODO); store.dispatch(LESS_TODO); unlistener()
当前应用的全部状态都保存在store的state树中,这是一个集合
想要修改state中的数据,必需要发送action,能够在任什么时候候调用dispatch发送action
action会做为第二个参数触发建立store时传入的Reducer函数,第一个参数是当前的state树
Reducer函数会根据action中的信息,返回一个新的state树存入store
这使得程序的运行在界面出现以前就变得能够预测:
UI组件使用初始的state树,当界面须要改变时,触发action,改变store中state树的数据,而后从新渲染显示redux