createStore用来生成Store,fn形式为(state, action) => state的纯函数,返回新的state而不是修改的
import { createStore } from ‘redux‘;
const store = createStore(fn);
Store对象包含所有数据,state就是Store在某个时刻的数据快照,当前时刻的state可以用store.getState()获取
import { createStore } from ‘redux‘; const store = createStore(fn); const state = store.getState()
改变内部 state 的唯一方法是 dispatch 一个 action(store.dispatch()),action只是一个用来描述已发生事件的对象
// action 可以被序列化,用日记记录和储存下来,后期还可以以回放的方式执行 store.dispatch({ type: ‘INCREMENT‘ }); // 1 store.dispatch({ type: ‘INCREMENT‘ }); // 2 store.dispatch({ type: ‘DECREMENT‘ }); // 1
store.dispatch({ type: ‘ADD_TODO‘, payload: ‘Learn Redux‘ });
引用官方原话-- 为了描述action如何改变state tree 需要编者reducers,Reducer只是一些纯函数(固定输入=>固定输出) 随着应用变大,可以把reducers拆成多个小reducers,分别独立操作state tree的不同部分
function visibilityFilter(state = ‘SHOW_ALL‘, action) { switch (action.type) { case ‘SET_VISIBILITY_FILTER‘: return action.filter default: return state } } function todos(state = [], action) { switch (action.type) { case ‘ADD_TODO‘: return [ ...state, { text: action.text, completed: false } ] case ‘COMPLETE_TODO‘: return state.map((todo, index) => { if (index === action.index) { return Object.assign({}, todo, { completed: true }) } return todo }) default: return state } } import { combineReducers, createStore } from ‘redux‘ let reducer = combineReducers({ visibilityFilter, todos }) let store = createStore(reducer)