Object.assign() 方法能够把任意多个的源对象自身的可枚举属性拷贝给目标对象,而后返回目标对象。语法以下:redux
Object.assign(target, ...sources)
Object.assign 方法只会拷贝源对象自身的而且可枚举的属性到目标对象身上。echarts
使用这个方法有个最须要注意的地方就是它是浅拷贝,也就是对于嵌套对象来讲使用Object.assign会直接替换掉。我在redux的项目中处理reducer中常常须要改变嵌套对象中的某个属性时候,最开始没有注意就出了错误。ui
下面是个人reducer代码:.net
const initialState = { mainMenu: "marketIndex", selectMenu: "equityMarket", externalInfoEchartsImage: "line", equityMarket: { tableData: [], refreshTable: false, tableFetching: true, rowIndex: 0, echartsData: [], echartsFetching: true, }, } export default function(state = initialState, action) { switch (action.type) { case types.SWITCH_EXTERNAL_MAIN_MENU: return Object.assign({}, state, { mainMenu: action.mainMenu }); case types.SELECT_EXTERNAL_SUB_MENU: return Object.assign({}, state, { selectMenu: action.selectMenu }); case types.REFRESH_EXTERNAL_DATA: return { ...state, [action.selectMenu]: { ...state[action.selectMenu], refreshTable: action.refreshTable, } }; ...
像mainMenu: "marketIndex"这种使用简单数据类型的,就能够直接使用Object.assign来改变属性的值。插件
Object.assign({}, state, { mainMenu: action.mainMenu });
而有嵌套数据类型的equityMarketcode
equityMarket: { tableData: [], refreshTable: false, tableFetching: true, rowIndex: 0, echartsData: [], echartsFetching: true, },
若是直接使用对象
Object.assign({}, state, equityMarket:{ refreshTable: action.refreshTable, });
那么就是直接将整个equityMarket替换了,所以须要用...扩展操做符来实现,或者用一些其余的插件等。blog
1.详细的用法介绍get