我正在尝试在应用程序中创建切换开关,而我是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
});
基本上是从reducer返回状态的COPY,而当返回{cards:[]}时,您将丢失该状态的所有其他props。在FIND_ALL,DELETE和Create CARD中对状态进行突变时,您还需要返回状态的其余部分。像这样编辑
case "FIND_ALL_CARDS":
return {
...state
cards: action.cards
};
在所有动作中都这样做,当您改变单个状态时,不要忘记传递先前的状态道具