初入redux -01

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的不同部分(reducers感觉就是根据action的type加工state后返回新的state. 个人觉得reducers就是state,为何这么说? reducers=> new state

// 如何理解reducers的拆分?比如主reducers的结构为
Store.state = {
  visibilityFilter: 'SHOW_ALL',
  todos: []
}
// 子reducers分别为 visibilityFilter和todus

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'
//然后借助redux的combineReducers函数来合并子reducers
let reducer = combineReducers({ visibilityFilter, todos }) let store = createStore(reducer)

 

posted @ 2018-02-05 16:44  SharkChilli  阅读(137)  评论(0编辑  收藏  举报