我正在尝试创建一个 reducer 来更新对象中的属性,但我无法更新和存储新的状态信息
减速器
export default function hideCardNumber(state = INITIAL_STATE, action: Action) {
if (action.type === 'HIDE_CARDNUMBER') {
return {
...state,
data: {...state.data, action }}
}
else
return state
}
行动
export const toggleViewNumberCard = (cardId: number, hideCardNumber: boolean) => {
return {
type: 'HIDE_CARDNUMBER',
cardId,
hideCardNumber,
}
}
派遣行动
function handleToggleViewCardNumber() {
cards.map((card: Card) => {
if (card.cardId === props.activeCard ) {
dispatch(toggleViewNumberCard(
card.cardId,
!card.hideCardNumber,
))
}
})
}
初始状态
export const INITIAL_STATE = {
activeCard: 0,
data: [
{
cardId: 0,
cardName: 'Card',
cardUsername: 'Name',
cardNumber: '1234 1234 1234 1234',
hideCardNumber: false, <-- Trying to replace this property when reducer update
},
]
}
答案 0 :(得分:1)
你需要像这样更新reducer:
const {hideCardNumber, cardId} = action;
return {
...state,
data: state.data.map(item => item.cardId === cardId ? {...item, hideCardNumber} : item )
}
答案 1 :(得分:0)
在实际场景中,cardID 将是一个哈希值。也为了在应用程序增长时轻松维护存储数据INITIAL_STATE应该是这样的。
export const INITIAL_STATE = {
activeCard: 0,
data: {
123456: {
cardId: 123456,
cardName: 'Card',
cardUsername: 'Name',
cardNumber: '1234 1234 1234 1234',
hideCardNumber: false,
},
}
}
那么 Reducer 就会是这样。
export default function hideCardNumber(state = INITIAL_STATE, action) {
if (action.type === 'HIDE_CARDNUMBER') {
return {
...state,
data: {
...state.data,
[action.cardId]: {
...state.data[action.cardId],
hideCardNumber: action.hideCardNumber
}
}
}
}
else
return state
}
如果 activeCard 与 cards 中的 ID 之一匹配,则代码将完美运行。
答案 2 :(得分:0)
首先最好将您的数据放入有效负载中,例如:
export const toggleViewNumberCard = (cardId: number, hideCardNumber: boolean) => {
return {
type: 'HIDE_CARDNUMBER',
payload : {
cardId,
hideCardNumber,
}
} }
看起来你有很多卡片,首先你必须找到你想要替换的当前卡片,如下所示:
const index = state.data.findIndex(
(card) => cardId === action.payload.cardId
);
然后复制你的旧数组:
const newArray = [...state.data];
然后用新的 hideCardNumber 值替换 newarray 的索引,如下所示:
newArray[index] = {
...newArray[index],
action.payload.hideCardNumber
};
return {
...state,
data: newArray,
};
希望对你有帮助