我有一个关于Redux的问题并更新嵌套对象的值。
让我们说这是我的初始状态:
const INITIAL_STATE = {
columnState: {
1: {
loading: false
},
2: {
loading: false
}
}
};
当我的减速机被召唤时:
case COLUMN_STATE_UPDATE:
const { type } = payload;
return {
...state
}
}
如何为特定ID更新loading
的值?假设我用key = 2更新条目,如何用key 2将loading
的值更改为true
for columnState对象,并返回新状态?
如果你的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
}
}
}
}
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中使用的标准命名约定