Redux 和 immutable js,我在尝试使用 immutable 后失去了状态
·
问题:Redux 和 immutable js,我在尝试使用 immutable 后失去了状态
在开始使用 reactjs 和 redux 进行开发后,我认为在使用 redux 时使用 immutable.js 会更好。
但是......也许我是智障或者需要一些练习才能正确使用它,一切都崩溃了。
如果你能帮助理解这里出了什么问题,那就太棒了!
所以,这是我的第一个代码:
export function posts(state = {
isFetching: true,
didInvalidate: false,
items: []
}, action) {
switch (action.type) {
case INVALIDATE_REQ:
return Object.assign({}, state, {
didInvalidate: true
});
case REQUEST_POSTS:
return Object.assign({}, state, {
isFetching: true,
didInvalidate: false
});
case RECEIVE_POSTS:
return Object.assign({}, state, {
isFetching: false,
didInvalidate: false,
items: action.posts
});
default:
return state;
};
};
我是这样改造的:
const initPostState = Map({
isFetching: true,
didInvalidate: false,
items: []
});
export function posts(state = initPostState, action) {
switch (action.type) {
case INVALIDATE_REQ:
return state.set('didInvalidate', true);
case REQUEST_POSTS:
return state.set({
isFetching: true,
didInvalidate: false
});
case RECEIVE_POSTS:
return state.set({
isFetching: false,
didInvalidate: false,
items: action.posts
});
default:
return state;
};
};
还有我的容器 MapStateToProps:
function mapStateToProps(state) {
const {
posts: isFetching,
posts
} = state.posts;
console.log(state);
...
所以问题是,我如何访问我的状态?状态控制台报告:

我迷路了!帮助!
解答
您需要使用immutableJS中的get方法
使用state.get('didInvalidate')访问didInvalidate的值,其他值类似。
如果您使用的是 javascript 对象,那么您可以像state.get('something').toJS()一样获取它
这样做应该给你的想法
function mapStateToProps(state){
const isFetching = state.get('isFetching'),
const items = state.get('items').toJS();
}
更多推荐
所有评论(0)