前面有一篇文章比较详细的介绍了redux,那么这篇文章主要是对redux中的几个角色进行深刻的理解。主要有如下几个部分:vue
const store = createStore(reducer)react
store中经常使用的三个方法:web
一个Action实际上是描述行为的数据结构,如一个ToDoList的应用结构。好比要增长一个ToDoItem,用action去描述:vuex
{ type:'ADD_TODO', text:'Build my first Redux App' }
那么怎么去更新以前的ToDoList,这时候就须要reduer,reducer实际上是一个纯函数(其输出结果只依赖于传入的参数)。这个函数通常接受两个参数:redux
action数据结构
function todoApp(state=initialState,action){ switch(action.type){ case ADD_TODO: return Object.assign({},state,{ todos:[ ...state.todos, { text:action.text, completed:false } ] }) break; default: return state } }
咱们知道一个reducer其实就是一个函数,若是你的应用中有多个reducer的话,那么如何将它们组合起来一块儿使用?这时候就须要combineReducers这个工具函数了。这个函数能够接受多个reducer做为参数,最终造成的是一个封装后的函数。这个封装后的函数其实也是一个reducer.函数
import {combineReducers} from 'redux' import todoApp from './todoApp' import counter from './counter' export default combineReducers({ todoApp, counter })
这个方法其实也是一个工具函数,能够帮助咱们去使用action工具
function addTodoWithDispatch(text){ const action = { type:ADD_TODO, text } dispatch(action) }
以上代码表示定义action的同时进行dispatch的操做ui
dispatch(addTodo(text)) dispatch(completeTodo(text))
那么使用bindCationCreators来实现以上的操做就简便不少,如:spa
const boundAddTodo = text => dispatch(addTodo(text)) const boundCompleteTodo = text => dispatch(completeTodo(text))
最终演示代码以下:
PureRedux.js
import React from 'react' import {createStore,bindActionCreators,combineReducers} from 'redux' function run(){ // init state const initialState = { count:0 } //create a reducer const counter = (state=initialState,action) => { switch(action.type){ case 'PLUS_ONE': return {count:state.count+1}; case 'MINUS_ONE': return {count:state.count-1}; case 'CUSTOM_COUNT': return{ count:state.count+action.payload.count } default: break; } return state } const todoApp = (state={}) => state //create store const store = createStore(combineReducers({ counter, todoApp })); //cation creator function flusOne(){ return {type:'PLUS_ONE'} } function minusOne(){ return {type:'MINUS_ONE'} } function customCount(count){ return {type:'CUSTOM_COUNT',payload:{count}} } flusOne = bindActionCreators(flusOne,store.dispatch) store.subscribe(() => console.log(store.getState())) // store.dispatch(flusOne()); flusOne(); store.dispatch(minusOne()) store.dispatch(customCount(5)) } export default () => ( <div> <button onClick={run}> Run </button> <p> --请打开控制台查看运行结果 </p> </div> )
App.js
import React from 'react' import PureRedux from './PureRedux' class App extends React.Component{ render(){ return( <div> <PureRedux></PureRedux> </div> ) } } export default App