问题
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