[英]Update value of nested Redux reducer object
我有一个关于Redux和更新嵌套对象的值的问题。
假设这是我的初始状态:
const INITIAL_STATE = {
columnState: {
1: {
loading: false
},
2: {
loading: false
}
}
};
当我的减速器被调用时:
case COLUMN_STATE_UPDATE:
const { type } = payload;
return {
...state
}
}
如何更新特定ID的loading
值? 假设我用键= 2更新了条目,如何使用键2将columnState对象的loading
值更改为true
,并返回新状态?
如果您的COLUMN_STATE_UPDATE
操作仅更新columnState
部分(假定payload
中的type
为键):
case COLUMN_STATE_UPDATE:
const { type } = payload;
return {
...state, // keep the other keys as they were
[type]: { // only update the particular one
loading: true
}
}
}
如果您的COLUMN_STATE_UPDATE
操作正在更新看起来像INITIAL_STATE
的整个状态(同样,假设payload
中的type
为键):
case COLUMN_STATE_UPDATE:
const { type } = payload;
return {
...state, // keep the other keys of state as they were
columnState: {
...state.columnState, // keep the other keys of columnState as they were
[type]: { // only update the particular one
loading: true
}
}
}
}
case COLUMN_STATE_UPDATE:
// payload = {type: 1, 1: {loading: true}}
const {type} = payload;
return {
columnState: {...state.columnState, [type]: payload[type] }}
};
以上可以实现为:
/**
* @param {Object} state The Global State Object of shape:
* @example
* const INITIAL_STATE = {
* columnState: {
* 1: {
* loading: false
* },
* 2: {
* loading: false
* }
* }
* };
* @param {Object} action The Action Object of shape
* @example
* let action = {type: 1, 1: {loading: true}};
* @returns {Function} The "slice reducer" function.
*/
function columnStateUpdate(state = {}, action) {
const {type} = action;
switch(type) {
case COLUMN_STATE_UPDATE:
return {
columnState: {...state.columnState, [type]: action[type] }}
};
}
}
我使用action
而不是payload
因为(state, action)
是Redux Docs中使用的标准命名约定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.