使用不可变 js 合并对象
Merging Objects with Immutable js
我在这里使用 React、Redux 和 Immutable。问题是关于将普通 Js 对象合并到 Immutable Map
obj.
正在导入 Immutable.js:
import { List as iList,
Map as iMap } from "immutable";
action.payload
是这样的:
{
Preview : {
tabClass : "tabPreview tab activeTab"
},
Body : {
tabClass : "tabBody tab"
},
Sleeve : {
tabClass : "tabSleeve tab"
}
};
用'Immutable.js'创建的InitialTabState
是这样的:
const initialTabState = iList.of(
iMap({
tabClass : "tabPreview tab activeTab",
tabName : "Preview"
}),
iMap({
tabClass : "tabBody tab",
tabName : "Body"
}),
iMap({
tabClass : "tabSleeve tab",
tabName : "Sleeve"
})
);
将顶部的action.payload
合并到上面的InitialTabState
中的reducer函数是这样的:
const tabsState = ( state = initialTabState, action ) => {
let payload = action.payload;
switch( action.type ) {
case( ENABLE_TAB ):
return (
state.map( (obj) => {
let curObjName = obj.get( "tabName" );
return (
obj.merge( payload[ curObjName ][ "tabName" ] )
);
})
);
...
};
然而,似乎什么也没有发生。我没有收到任何错误,输出对象与 InitialTabState 相同,当其中的 属性 tabClass
应根据来自 Immutable.js.
的合并函数更改时
obj.merge( payload[ curObjName ][ "tabName" ] )
合并负载中不存在的 属性。我相信您想要 obj.merge( payload[ curObjName ])
,这将更新选项卡的 类。
我在这里使用 React、Redux 和 Immutable。问题是关于将普通 Js 对象合并到 Immutable Map
obj.
正在导入 Immutable.js:
import { List as iList,
Map as iMap } from "immutable";
action.payload
是这样的:
{
Preview : {
tabClass : "tabPreview tab activeTab"
},
Body : {
tabClass : "tabBody tab"
},
Sleeve : {
tabClass : "tabSleeve tab"
}
};
用'Immutable.js'创建的InitialTabState
是这样的:
const initialTabState = iList.of(
iMap({
tabClass : "tabPreview tab activeTab",
tabName : "Preview"
}),
iMap({
tabClass : "tabBody tab",
tabName : "Body"
}),
iMap({
tabClass : "tabSleeve tab",
tabName : "Sleeve"
})
);
将顶部的action.payload
合并到上面的InitialTabState
中的reducer函数是这样的:
const tabsState = ( state = initialTabState, action ) => {
let payload = action.payload;
switch( action.type ) {
case( ENABLE_TAB ):
return (
state.map( (obj) => {
let curObjName = obj.get( "tabName" );
return (
obj.merge( payload[ curObjName ][ "tabName" ] )
);
})
);
...
};
然而,似乎什么也没有发生。我没有收到任何错误,输出对象与 InitialTabState 相同,当其中的 属性 tabClass
应根据来自 Immutable.js.
obj.merge( payload[ curObjName ][ "tabName" ] )
合并负载中不存在的 属性。我相信您想要 obj.merge( payload[ curObjName ])
,这将更新选项卡的 类。