combineReducers优化合并reducer
原始臃肿写法
接上一篇博客:Redux 之 状态管理库 – 核心api
当数据过于臃肿时,可以用组件化的方式提出来写,再进行合并
- 原始臃肿写法,数据很多时,写法会非常杂,不建议使用。
X X X
例如:index 的数据要管理、message 的数据要管理、list 的数据要管理
function reducer(state={
index:{info:"首页的数据"},
list:{info:"列表的数据"},
message:{info:"留言页的数据"}
},action){
switch(action.type){
case "index_edit_info":
return{
...state,
index:action.info
}
// ...
// ..
// .
}
return state
}
- 当数据过于臃肿时,可以用组件化的方式提出来写,再进行合并。
√ √ √
合并写法1
import React from 'react';
import { createStore } from "redux";
// 1. 每个部分分开,先用组件化的方式提出来写
function index(state={info:"首页"},action){
switch(action.type){
case "index_edit_info":
return{
...state,
info:action.info
}
}
return state
}
function list(state={list:"列表",message:"详情"},action){
switch(action.type){
case "list_edit_info":
return{
...state,
list:action.list,
// message:action.message
}
case "message_edit_info":
return{
...state,
message:action.message
}
}
return state
}
// 2. 合并到一起
// (1)合并写法一 ---------------------------
function reducer(state={},action){
return{
index:index(state.index,action),
list:list(state.list,action)
}
}
let store = createStore(reducer);
store.subscribe(()=>{
console.log(store.getState());
})
store.dispatch({
type:"index_edit_info",
info:"啦啦啦"
});
store.dispatch({
type:"list_edit_info",
list:"我是一个列表",
// message:"我是一个列表的详情"
});
store.dispatch({
type:"message_edit_info",
message:"我是一个列表的详情"
})
function App() {
return (
<div>哈哈</div>
);
}
export default App;
合并写法2,combineReducers 终极简洁版
使用 combineReducers
,把 reducer
的函数换成下边这种写法,会更加简洁!!!
参数: 传入一个对象,这个对象中的属性,就是要合并的reducer
注意点: 对象的属性名,要和函数名相同
import React from 'react';
import { createStore,combineReducers } from "redux";
...
// (2)合并写法二:终极简洁版 ---------------------------
let reducer = combineReducers({
index,
list
});
let store = createStore(reducer);
store.subscribe(()=>{
console.log(store.getState());
})
...
浏览器输出:(两种合并方式效果都一样)