【发布时间】:2016-09-28 10:05:18
【问题描述】:
我想尝试练习如何使用immutable.js
但我不知道如何将我的减速器编辑为不可变的方式。 (我尝试在 github 上找到一些代码,但它们是基本的)
而且我的组件也有错误。
所以我想寻求帮助来指导我如何重构我的reducer?
这是我原来的 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') 来获取 state 的 box 属性,然后你可以在该数组上使用 map。
标签: reactjs redux immutable.js