[英]Javascript Redux update nested object property value
I have a question. 我有个问题。 How can I update my value in my nested object ?
如何在嵌套对象中更新我的值?
so my Redux state looks like: 所以我的Redux状态看起来像:
const initialState = {
elements: [],
selectedElement: {},
};
In elements array I will storage my "elements" with structure like this: 在元素数组中,我将使用如下结构存储我的“元素”:
{
id: 3243,
elemType: 'p',
content: 'some example content',
style: {
fontSize: 30,
color: "red",
textDecoration: "underline",
fontFamily: "Arial"
}
}
And now I'd like change values in style. 而现在我想改变风格的价值观。 Maybe fontSize, maybe color... depends which property will be selected.
也许fontSize,也许是颜色......取决于选择哪个属性。
I've made action creator which give me id, property, value for these changes.. but the problem is that I don't know how to exactly write code in reducer :( 我已经制作了动作创建者,它给了我这些变化的id,属性,值..但问题是我不知道如何在reducer中准确编写代码:(
Action Creator 动作造物主
export const updateElement = (property, value, id) => {
return {
type: 'UPDATE_ELEMENT',
property,
value,
id
}
}
Reducer 减速器
const {id, elemType, content, style, type, selected, property, value} = action;
case 'UPDATE_ELEMENT':
const elementForUpdate = state.elements.find(element => element.id === id);
console.log(id, property, value);
return ...?
In short, you have to maintain immutability . 简而言之,你必须保持不变性 。 In your case, you have to make sure that:
在您的情况下,您必须确保:
elements
array is copied. elements
数组被复制。 style
object of the updated element is copied. style
对象。 You can accomplish all of these with a single map
: 您可以使用单个
map
完成所有这些操作:
case 'UPDATE_ELEMENT': {
const elements = state.elements.map(el => {
if (el.id === id) {
const style = { ...el.style, [property]: value };
return { ...el, style };
} else {
return el;
}
});
return { ...state, elements };
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.