欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
redux优势
 
所有东西(Store,Action Creator,config)都可以hot-reload
 
防止一些常见的反模式
 
很容易做到同构,不用单例模式,数据可复用性好
 
可以接受任何形式的数据:JS Object,Array,ImmutableJs..
 
简化至一个Store,不用考虑多个store的管理
 
提供redux-tools time travel工具容易debug
 
可以用middleware 扩充dispatch
 
不用mock就可以很容易的测试
 
三要素
 
ACTION
 
一个普通的js Object,参见Flux Standard Action 一个标准的action是什么样子的:
 
MUST type, 常量,表示动作类型
 
MAY payload, error,meta
 
{
 
  type:SEND_MESSAGE,
 
  payload:{ text:'Hello World' }
 
}
 
通常我们会为action 写一个actionCreator的纯函数来创建他们。我们可以把不同业务的actionCreator 放在不同的js文件里面。
 
通常我们会创建一个叫做action(鄙人不喜欢用复数形式的命名)的文件夹来存放这些actionCreator
 
function sendMessage (text) {
 
   return {
 
     type:'SEND_MESSAGE',
 
     text
 
   }
 
}
 
这样的纯函数很好测试
 
expect(sendMessage('Hello Damon')).to.deep.equal({
 
   type: SEND_MESSAGE,
 
   payload:{
 
     text:'Hello Damon'
 
   }
 
})
 
要触发这个 sendMessage的action 只需要调用Store.dispatch(sendMessage('Hello World'));
 
使用thunkMiddleware,PromiseMiddleware 可以延展Action Creator的功能,这边先不做叙述。
 
Reducer
 
Reducer 给Store初始的state,并根据收到的action回传新的state,和flux的store的部分工作一样。
 
(oldState, action)=>newState
 
每次接收到dispatch的action,就会触发reducer,根据oldState回传新的state,这样就可以简洁的表达如何变更state了:
 
const initialState = {
 
   message:''
 
}
 
function messageReducer(state=initialState, action) {
 
  switch(action.type){
 
     case SEND_MESSAGE:
 
         return{...state, message:action.text}
 
     default:
 
        return state
 
   }
 
}
 
我们用了Object spread 语法 来确保我们不会破坏oldState而返回一个新的state
 
对于不需要处理的action直接返回state
 
Reducer 也是一个纯函数,不要试图做一些side-effect的事情(修改old state,请求API,调用非纯函数 Date.now() Math.random()等)
 
Store
 
Store 是连接Action和Reducer的地方,作用:
 
保存state树,整个应用只有一个
 
getState 来获取state
 
dispatch来发送Action更改state
 
subscribe() 注册回调函数监听state
 
创建Store
 
import {createStore} from 'redux'
 
import messageReducer from '../reducer/message'
 
const store = createStore(messageReducer);
 
//也可以指定一个初始化的 initialState 
 
// createStore(messageReducer, initialState);
 
生产过程中也会遇到有很多的reducer,所以我们需要用combineReducers来结合它们
 
import { createStore, combineReducers } from 'redux';
 
import * as reducers from '../reducers';
 
const reducer = combineReducers(reducers);
 
const store = createStore(reducer);
 
数据流
 
store.dispatch(action) -> reducer(state, action) -> store.getState()
 
MIDDLEWARE
 
延展dispatch的功能
 
import { createStore, applyMiddleware } from 'redux';
 
const store =
 
applyMiddleware(promise, thunk, observable)(createStore)(reducer);
 
这样dispatch 将被一个个的middleware装饰。

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h63712.shtml