[英]deep change state with variable index
I'm trying to follow the instructions found in Cleaner/shorter way to update nested state in Redux? 我正在尝试按照更清洁/更简短的方法中的说明更新Redux中的嵌套状态? [the accepted answer]
[公认的答案]
The thing is in my particular case, i have a layer that really depends on which model the user has selected up to that point. 关键是在我的特定情况下,我的图层实际上取决于用户选择的模型。 My structure:
我的结构:
Now in my reducer, i've tried (just want to change the favorite leaf to true): 现在在我的reducer中,我已经尝试过(只是想将最喜欢的叶子更改为true):
let newStateForFavorites = {...state, models: {
...state.models,
62416: {
...state.models.62416,
details: {
...state.models.62416.details,
favorited: true
}
}
}};
Javascript complains. Javascript抱怨。 If i try to extract it to a var:
如果我尝试将其提取到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 does not associate the const. Javascript不关联const。 And it errors out -currentModelToFav is undefined-
它会出错-currentModelToFav未定义-
Ideas of what i'm doing wrong? 我在做什么错的想法? Thanks!
谢谢!
If you want to use a variable as a property name you'll have to use these constructs: 如果要使用变量作为属性名称,则必须使用以下构造:
{[variableName] : value}
and 和
{propertyName : variable[variableName]}
So, your object literal will become: 因此,您的对象文字将变为:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {...state, models: {
...state.models,
[currentModelToFav]: {
...state.models[currentModelToFav],
details: {
...state.models[currentModelToFav].details,
favorited: true
}
}
}};
You need to use bracket notation to pull an object key using a variable: 您需要使用括号符号来使用变量拉对象键:
const currentModelToFav = action.payload.model_id;
let newStateForFavorites = {
...state,
models: {
...state.models,
[currentModelToFav]: {
...state.models[currentModelToFav],
details: {
...state.models[currentModelToFav].details,
favorited: true
}
}
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.