简体   繁体   中英

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:

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.

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 :(

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:

  1. The elements array is copied.
  2. The updated element object is copied.
  3. The style object of the updated element is copied.

You can accomplish all of these with a single 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 };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM