react-redux 從 store 刪除指定id物件
action 定義
reducer 寫法
說明
聚焦在
1. assign()這個函式會在第一個參數new一個物件出來,而後面的東西都會被複製一分到前面去。
2. filter()這個函示則是當成立的時候該逸代值被回傳(跟map()做一下聯想),所以當action.id與item.id相等的時候便不成立(!==),因此不被回傳。該物件被刪除
參考
https://rhadow.github.io/2015/07/30/beginner-redux/
export function removeCartItem(id){
return{
type:REMOVE_CART_ITEM,
id:id
};
}
reducer 寫法
export default (state = initstate(), action) => {
console.log('userReducer was called with state', state, 'and action', action);
switch (action.type) {
case GET_CART_ITEMS:
return assign({}, state, {
cartItems: action.items
});
case REMOVE_CART_ITEM:
return assign({},{
cartItems:state.cartItems.filter(
//return value without target id
(item) => {
console.log('act:'+action.id);
console.log('item:'+item.id);
return item.id !== action.id;
}
)
});
default:
return state;
}
};
說明
聚焦在
case REMOVE_CART_ITEM:這邊
1. assign()這個函式會在第一個參數new一個物件出來,而後面的東西都會被複製一分到前面去。
2. filter()這個函示則是當成立的時候該逸代值被回傳(跟map()做一下聯想),所以當action.id與item.id相等的時候便不成立(!==),因此不被回傳。該物件被刪除
參考
https://rhadow.github.io/2015/07/30/beginner-redux/
留言
張貼留言