安裝react
npm install --save reduxnpm
react綁定庫和開發者工具redux
npm install --save react-redux npm install --save-dev redux-devtoolsapi
幾個概念:函數
如何建立Redux store存放應用狀態,api是 { subscribe, dispatch, getState };工具
let store = createStore(reducer)spa
能夠訂閱更新,也能夠將事件綁定到視圖層對象
store.subscribe(() => {console.log( store.getState() );})
state具體是怎麼樣的?事件
{ todos: [{text: 'Eat food',completed: true}, {text: 'Exercise',completed: false}],visibilityFilter: 'SHOW_COMPLETED' }
改變內部state的方法是dispatch一個action,action 能夠序列化保存,以便回放ci
store.dispatch({ //action描述當前發生的事,爲一個對象,type是必須屬性type: 'INCREMENT',payload: 'Learn Redux'})
reducer把action,state串起來,用來管理整個應用的state;
function visibilityFilter(state = 'SHOW_ALL', action) {if (action.type === 'SET_VISIBILITY_FILTER') {return action.filter;} else {return state;}}function todos(state = [], action) {switch (action.type) {case 'ADD_TODO':return state.concat([{ text: action.text, completed: false }]);case 'TOGGLE_TODO':return state.map((todo, index) =>action.index === index ? { text: todo.text, completed: !todo.completed } : todo)default: return state;}}
function todoApp(state = {}, action) {return {todos: todos(state.todos, action),visibilityFilter: visibilityFilter(state.visibilityFilter, action)};}
import { combineReducers, createStore } from 'redux'let reducer = combineReducers({ visibilityFilter, todos })let store = createStore(reducer)
fff