Action 創(chuàng)建函數(shù)
編寫
function increment(){
return { type: 'INCREMENT' }
}
發(fā)起
store.dispatch( increment() )
如果不想每次都 store.dispatch 發(fā)起 action.
const increment = () => dispatch( increment() )
_使用 react-redux 將 action 創(chuàng)建函數(shù)綁定到 React 組件上時, bindActionCreators() 方法自動將多個 action 創(chuàng)建函數(shù)封裝成可以直接調(diào)用的普通函數(shù) _
意義
Action 創(chuàng)建函數(shù)更大的意義在于封裝邏輯, 而不是創(chuàng)建 action 對象, 比如說可以在里面添加一些判斷邏輯(只允許奇數(shù)相加等). 使用 action 創(chuàng)建函數(shù)封裝邏輯是 react 與 redux 配合的最佳實踐. 當(dāng)所有邏輯被轉(zhuǎn)移到 redux后, react 就只負(fù)責(zé)渲染界面, 并發(fā)起 action.
中間件會讓 action 創(chuàng)建函數(shù)返回更多的格式( 函數(shù) ), 增強(qiáng) action 創(chuàng)建函數(shù)的功能, 并讓它處理負(fù)責(zé)邏輯.
Redux Thunk 中間件
redux thunk 中間件可以讓 action 創(chuàng)建函數(shù)先不返回 action 對象, 而是返回一個函數(shù).
通過這個函數(shù)延遲 dispatch 或 某些情況下才 dispatch. 這個內(nèi)部函數(shù)接受 store 的兩個方法 dispatch 和 getState 作為參數(shù).
function incrementIfOdd(){
return ( dispatch, getState() ) => {
const value = getState();
if (value % 2 === 0){
return;
}
dispatch( increment() );
}
}
要使用, 先激活
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
const store = createStore( counter, applyMiddleware( thunk ) );
function increment(){
return { type: 'INCREMENT' }
}
function incrementIfOdd(){
return ( dispatch, getState() ) => {
const value = getState();
if (value % 2 === 0){
return;
}
dispatch( increment() );
}
}
function incrementAsync(){
return ( dispatch ) => {
setTimeout( ()=>{
dispatch( increment() ) ;
} )
}
}
// 發(fā)起action, 上面三個都是 action 創(chuàng)建函數(shù)
store.dispatch( increment() )
store.dispatch( incrementIfOdd() )
store.dispatch( incrementAsync() )