Last active
September 15, 2016 08:35
-
-
Save tingwei628/48081b991f0658ae59c5 to your computer and use it in GitHub Desktop.
[ReactJS][Redux]動態增加/刪除陣列內元素
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
reducer 寫法參考:https://github.com/rackt/redux/blob/master/examples/todos-with-undo/reducers.js | |
說明: Redux負責儲存 陣列狀態 | |
用Immutable方式 | |
意思是"不要汙染(改變)原本在reducer的舊的state | |
而是創造一個全新的state回傳, 且舊的state不影響 | |
另外,注意刪減時, Rowt 要有key值 | |
*/ | |
//這是一個 叫做clickAction的Reducer | |
//初始狀態是state={'rows':[(Rowt)]}; Rowt 是html tag | |
//stateNew 是全新的狀態 | |
function clickAction(state={'rows':[<Rowt key={0}/>]}, action){ //增加 或 減少人數 | |
switch(action.type){ | |
case ADD_MEMBER: //增加元素 | |
function newKey(rows){ | |
var bKey = 0 | |
for(var i =0 ; i<rows.length; i++){ | |
if(parseInt(rows[i].key) > bKey){ | |
bKey = parseInt(rows[i].key) | |
} | |
} | |
return bKey; //回傳最大的key值 | |
} | |
var rowNewKey = newKey(state.rows); | |
var stateNew ={'rows':state.rows.concat(<Rowt key={rownewKey+1}>)}; //用concat 方式增加, 最新key值 是rownewKey+1 | |
return Object.assign({},state,stateNew); | |
case CUT_MEMBER: //減少任一index元素 | |
// 方法1沒效喔, state沒帶進去 2015/12/01 | |
//var arr= state.rows.slice(0,action.index).concat(state.rows.slice(action.index+1, state.rows.length)), //slice immutable | |
// stateNew={'rows':arr}; | |
// return Object.assign({},state ,stateNew); | |
//方法2 {'rows':[...state] 有用 | |
return {'rows':[...state.rows.slice(0,action.index),...state.rows.slice(action.index+1)]}; | |
default: | |
return state; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment