这个元素的状态是第一次未定义?

The state of this element is Undefined for first time?

我正在尝试在我的应用程序中创建切换开关,我是 redux 的新手。在非常努力地寻找每个地方 online.Please 帮助之后发布这个问题。 我的 Reducer 如下:

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

我的组件连接正确

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

我第一次切换开关时未定义,但在第一次切换后我得到了状态。 请帮我解决这个问题

基本上从 reducer 中,你正在 return 复制你的状态,当你 return {cards: []} 时,你将丢失状态中的所有其余道具。 当您在 FIND_ALL、DELETE 和 Create CARD 中改变状态时,您还需要 return 保留状态的一部分。像这样编辑

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

在所有动作中都这样做,当你改变单个状态时不要忘记传递以前的状态