[英]Update value of nested Redux reducer object
I have a question regarding Redux and updating a value of a nested object. 我有一个关于Redux和更新嵌套对象的值的问题。
Let's say this is my initial state: 假设这是我的初始状态:
const INITIAL_STATE = {
columnState: {
1: {
loading: false
},
2: {
loading: false
}
}
};
When my reducer is called: 当我的减速器被调用时:
case COLUMN_STATE_UPDATE:
const { type } = payload;
return {
...state
}
}
How do I update the value of loading
for the particular id? 如何更新特定ID的
loading
值? Let's say that I update entry with key = 2, how do I change the value of loading
to true
for columnState object with key 2, and return the new state? 假设我用键= 2更新了条目,如何使用键2将columnState对象的
loading
值更改为true
,并返回新状态?
If your COLUMN_STATE_UPDATE
action is updating only the columnState
part (assuming type
in your payload
as the key): 如果您的
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
}
}
}
If your COLUMN_STATE_UPDATE
action is updating the entire state that looks like INITIAL_STATE
(again, assuming type
in your payload
as the key): 如果您的
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] }}
};
The above could be implemented as: 以上可以实现为:
/**
* @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] }}
};
}
}
I use action
instead of payload
because (state, action)
is standard naming convention used in Redux Docs 我使用
action
而不是payload
因为(state, action)
是Redux Docs中使用的标准命名约定
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.