我试图按照Cleaner/shorter way to update nested state in Redux? [已接受的答案]中的说明进行操作
事情就是在我的特殊情况下,我有一个层,它实际上取决于用户在那一点上选择的模型。我的结构:
现在在我的reducer中,我已经尝试过(只想将最喜欢的叶子更改为true):
let newStateForFavorites = {...state, models: {
...state.models,
62416: {
...state.models.62416,
details: {
...state.models.62416.details,
favorited: true
}
}
}};
Javascript抱怨。如果我尝试将其提取到var:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {...state, models: {
...state.models,
currentModelToFav: {
...state.models.currentModelToFav,
details: {
...state.models.currentModelToFav.details,
favorited: true
}
}
}};
Javascript不关联const。而且错误out -currentModelToFav未定义 -
我做错了什么的想法?谢谢!
答案 0 :(得分:5)
如果您想将变量用作属性名称,则必须使用这些构造:
{[variableName] : value}
和
{propertyName : variable[variableName]}
因此,您的对象文字将变为:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {...state, models: {
...state.models,
[currentModelToFav]: {
...state.models[currentModelToFav],
details: {
...state.models[currentModelToFav].details,
favorited: true
}
}
}};
答案 1 :(得分:1)
您需要使用bracket notation使用变量拉取对象键:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {
...state,
models: {
...state.models,
[currentModelToFav]: {
...state.models[currentModelToFav],
details: {
...state.models[currentModelToFav].details,
favorited: true
}
}
}
};