变量索引

时间:2018-03-22 20:27:07

标签: javascript reactjs redux

我试图按照Cleaner/shorter way to update nested state in Redux? [已接受的答案]中的说明进行操作

事情就是在我的特殊情况下,我有一个层,它实际上取决于用户在那一点上选择的模型。我的结构:

my structure

现在在我的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未定义 -

我做错了什么的想法?谢谢!

2 个答案:

答案 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
            }
        }
    }
};