这个元素的状态是第一次未定义? [英] The state of this element is Undefined for first time?

查看:39
本文介绍了这个元素的状态是第一次未定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的应用程序中创建切换开关,我是 redux 的新手.在非常努力并在网上四处寻找之后发布了这个问题.请帮忙.我的减速机如下:

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

推荐答案

基本上从 reducer 返回一个状态的 COPY,当你返回 {cards: []} 时,你将失去所有剩余的 props状态.当您在 FIND_ALL、DELETE 和 Create CARD 中改变状态时,您还需要返回状态的其余部分.像这样编辑

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

这篇关于这个元素的状态是第一次未定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆