我想嘗試練習如何使用immutable.js
但我不知道如何編輯我的reducer以不可變的方式。 (我嘗試在github上找到一些代碼,但它們很基本)
而且我的組件也有錯誤。
所以我想要求幫忙來指導我如何重構我的reducer?如何轉換redux與immutable.js
這是我原來的reducer.js
原reducer.js
import * as TYPE from '../constants/ActionTypes';
const INIT_STATE = {
box: [
{ 'id': 1,
'axisX': 10,
'axisY': 10,
'width': 200,
'height': 200,
},
{ 'id': 2,
'axisX': 20,
'axisY': 300,
'width': 200,
'height': 200,
}
]
};
export default function editZone(state = INIT_STATE, action) {
let newState = null;
switch (action.type) {
case TYPE.UPDATE_POSITION:
newState = Object.assign({}, state);
newState.box = newState.box.map(box => {
if (box.id === action.payload.id) {
box.axisX = action.payload.x;
box.axisY = action.payload.y;
}
return box;
});
return newState;
default:
return state;
}
}
我編輯使用immutable.js
,我只需要添加包裹INIT_STATE
與fromJS()
**不變reducer.js **
import {List, Map, fromJS} from 'immutable';
const INIT_STATE = fromJS({
box: [
{ 'id': 1,
'axisX': 10,
'axisY': 10,
'width': 200,
'height': 200,
},
{ 'id': 2,
'axisX': 20,
'axisY': 300,
'width': 200,
'height': 200,
}
]
});
我面臨着一個錯誤:TypeError: Cannot read property 'map' of undefined
我盡力勸慰輸出this.props.editZone
它顯示Map {size: 2, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}
我怎樣才能解決這個問題?
boxComponent.js
const boxes = this.props.editZone.box;
const playgroundObjetcs = boxes.map(box => {
return (...)
});
首先在reducer裏面使用state.get('box')來獲得狀態的box屬性,然後你可以在該數組上使用map。 –