用物件展開來寫物件操作的純函式
阿新 • • 發佈:2019-01-11
純函式的一個原則是“不會產生副作用”。
一、陣列操作
定義
1 const state = { 2 cart: [ 3 { 4 product: 'bread 700g', 5 quantity: 2, 6 unitCost: 1 7 }, 8 { 9 product: 'milk 500ml', 10 quantity: 1, 11 unitCost: 2 12 }, 13 { 14 product: 'app 500g',15 quantity: 1, 16 unitCost: 3 17 } 18 ]
增
1 let push = () => { 2 let item = { 3 product: 'cake 500g', 4 quantity: 3, 5 unitCost: 49 6 } 7 return { 8 ...state, //展開state 9 cart: [ //解構得到 cart 10 ...state.cart, //展開cart 11 item //在末尾增加item 12 ] 13 } 14 }
1 let unshift = () => { 2 let item = { 3 product: 'cake 500g', 4 quantity: 3, 5 unitCost: 49 6 } 7 return {...state,cart: [item, ...state.cart]} 8 }
刪
1 let removeAt = (index) => { 2 return{ 3 ...state, 4 cart: [ 5 ...state.cart.slice(0, index), 6 ...state.cart.slice(index + 1) 7 ] 8 } 9 }
改
1 let changeAt = (index, item) => { 2 return { 3 ...state, 4 cart: [ 5 ...state.cart.slice(0, index), 6 item, 7 ...state.cart.slice(index + 1) 8 ] 9 } 10 }
二物件操作
定義
1 const state = { 2 product: 'bread 700g', 3 quantity: 2, 4 unitCost: 1 5 }
增
1 let add = () => { 2 let price = '2.00' 3 return { 4 ...state, //展開state 5 price 6 } 7 }
刪
1 let _delete = () => { 2 return JSON.parse(JSON.stringify({ 3 ...state, 4 unitCost: undefined 5 })) 6 }
改
1 let change = () => { 2 return { 3 ...state, 4 unitCost: 2 5 } 6 }