閱讀 redux 原始碼的時候,發現 redux 給我們提供了一系列方法,
- createStore ( redux 創建 store; 必備 )
- applyMiddleware ( redux 注入中間件 )
- compose ( redux 組合多個中間件)
下面這兩個方法是干啥用的呢?
- bindActionCreators
- combineReducers
一、bindActionCreators
1. 定義 action 檔案
一個檔案定義多個 action 方法,一般跟某一個業務相關的 action 放在同一個檔案中,
//action.js
export const Action1 = () => {
return { type: "action", payload: "Action1" };
};
export const Action2 = () => {
return (dispatch) => {
dispatch({ type: "action", payload: "Action2" });
};
};
export const Action3 = () => {
return { type: "action", payload: "Action3" };
};
...
2. 一般的action系結方式
// App.jsx
import * as actions from "./action";
export default connect(
(state) => state,
(dispatch) => {
//回傳一個 action 集合物件
return {
Action1: () => dispatch(actions.Action1()),
Action2: () => dispatch(actions.Action2()),
Action3: () => dispatch(actions.Action3()),
...
};
}
)(App);
一般 action 比較少的時候用這種方式系結還能接受,如果對于復雜的專案,一個業務需要系結的 action 超過10個甚至更多,還用這種羅列式系結不僅代碼重復而且繁重,
圖片可以看出 react-redux 將 action 成功的系結到了 props 屬性上,
3. bindActionCreators 使用
// App.jsx
import { bindActionCreators } from "redux";
import * as actions from "./action";
export default connect(
(state) => state,
(dispatch) => {
return {
...bindActionCreators(actions, dispatch),
};
}
)(App);

使用 bindActionCreators 系結 action 一行代碼就搞定,
有的人不喜歡把 action 方法直接放在 props 第一層,那么我再套一層就好了
// App.jsx
import { bindActionCreators } from "redux";
import * as actions from "./action";
export default connect(
(state) => state,
(dispatch) => {
return {
actions: bindActionCreators(actions, dispatch),
};
}
)(App);
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-QRY7EBoV-1606903973083)(https://i.loli.net/2020/12/02/zyjAb89aMiCVXNS.png)]
connect 方法會把方法回傳的物件系結到 props 上,那么只要我搞定,我可以無線套娃,
export default connect(
(state) => state,
(dispatch) => {
// 回傳的內容直接系結到 props
return {
//無線套娃
action1: {
action2: bindActionCreators(actions, dispatch),
},
};
}
)(App);
[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-OsJ7LT3j-1606903973085)(https://i.loli.net/2020/12/02/Hrf87jwiKSFTznM.png)]
二、combineReducers
createStore 方法創建新 store 需要傳入一個 reducer 方法 ,但是復雜的業務需要把 reducer 區分開,但是 createStore 只能接受一個 reducer, 需要把多個 reducer 合并成同一個,combineReducers 方法就是為了合并 reducer,
import { createStore, combineReducers } from "redux";
// 此處偷懶,把多個 reducer放在一起了
//第一個 reducer
const oneReducer = (state = {}, action) => {
switch (action.type) {
case "action":
return { ...state, actions: action.payload };
case "levenx":
return { ...state, AB: action.payload };
default:
return state;
}
};
// 第二個 reducer
const twoReducer = (state = {}, action) => {
switch (action.type) {
case "action":
return { ...state, actions: action.payload };
case "levenx":
return { ...state, AB: action.payload };
default:
return state;
}
};
.... // N 個reducer
const reducer = combineReducers({
one: oneReducer,
two: twoReducer });
// 創建 store 實體
const store = createStore(reducer, {});
export { store };
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/229939.html
標籤:其他
上一篇:泛在網技術考點整理
