The state of this element is Undefined for first time?

牧云@^-^@ 提交于 2020-03-03 07:48:46

问题


I am trying to create toggle switch in my application and i am new to redux. Posting this question after trying very hard and looking eveywhere online.Please help. My Reducer is below:

const initialState = {
    preview: "off",
    cards:
};

const cardReducer = (state = initialState, action) => {
        switch (action.type) {

            case "FIND_ALL_CARDS":
                return {
                    cards: action.cards
                };
            case "DELETE_CARD":
                return {
                    cards: state.cards.filter(card => card.id !== action.cardId)
                };
            case "CREATE_CARD":
                return {
                    cards: [...state.cards, action.card]
                };
            case "PREVIEW":
                console.log(state); // I get cards[] in the state but no preview.
                let swtch = "on";
                if (state.preview === "on") {
                    swtch = "off";
                }
                console.log(state.preview); // Undefined 

                return {
                    cards: state.cards,
                        preview: swtch
                };
            default:
                return state;
        }

I have connected properly in my component

const stateToPropertyMapper = state => ({
  cards: state.cards.cards,
  preview: state.cards.preview
});

I get undefined for the first time i toggle the switch but after first toggle i get the state. Please help me on this


回答1:


Basically from reducer you are returning a COPY of your state, and when you return {cards: []}, you are losing all of the rest props from the state. When you are mutating state in FIND_ALL, DELETE and Create CARD you need to return rest part of the state as well. Edit like this

case "FIND_ALL_CARDS":
    return {
        ...state
        cards: action.cards
     };

Do it in all actions, dont forget to pass previous prop of state when u mutate single one



来源:https://stackoverflow.com/questions/60334631/the-state-of-this-element-is-undefined-for-first-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!