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

问题描述 投票:1回答:1

我正在尝试在应用程序中创建切换开关,而我是redux的新手。经过非常努力并在网上寻找任何地方后,发布此问题。请提供帮助。我的减速机如下:

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.cards
});

我第一次切换开关时未定义,但是第一次切换后,我得到了状态。请帮我enter image description here

javascript reactjs redux react-redux web-deployment-project
1个回答
0
投票

基本上是从reducer返回状态的COPY,而当返回{cards:[]}时,您将丢失该状态的所有其他props。在FIND_ALL,DELETE和Create CARD中对状态进行突变时,您还需要返回状态的其余部分。像这样编辑

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

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

© www.soinside.com 2019 - 2024. All rights reserved.