我对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
并返回新状态?
答案 0 :(得分:1)
如果您的COLUMN_STATE_UPDATE
操作仅更新了columnState
部分
(假设您的type
中的payload
为密钥)
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
的整个状态(同样,以您type
中的payload
为键):
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
}
}
}
}
答案 1 :(得分:0)
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中使用的标准命名约定