2016-06-27 31 views
1

我减速终极版和Immutable.js - 从JSON

var initialState = Map({ 
status: true 
}); 
function user(state = initialState, action) { 
switch (action.type) { 
    case GET_PROFILE: 
    return state.set(fromJS(action.response)) 
    } 
    }) 

API集状态返回JSON - >action.response

{ 

    "id": 11, 
    "profileImage": "http://www.surfertoday.com/images/stories/addictivesurfing.jpg" 

} 

问题:fromJS设置,而不是一个新的Map对象,将数据添加到现有Map。我试图做一些像 return state.set(Array(fromJS(action.response)))这不起作用。


我该如何解决这个问题?或者我不应该使用Immutable.js?

+0

使用'merge',而不是'set' – user6227254

回答

1

嗯,从技术上讲,你确实希望它返回一个新的地图,因为redux/immutable的要点是你要用你的更改返回一个新的状态对象,而不是改变现有的对象。

很难说为什么这不适合你,因为我不确定你想要做什么。我认为案例“GET_PROFILE”可能可以重新命名为更具体的东西?

这个例子并不是完美的,但可以给你一些启示:https://github.com/rogic89/ToDo-react-redux-immutable/blob/master/src/reducers/todos.js

如果您发布更多信息或添加更多的代码我可能能够提供更深入的了解。

0

您可能试图做的是更新从某种请求中检索到的新值的状态。

您在减速器中编写的动作并未使用新值更新存储器。

Immutable.js Map/set函数需要两个参数键和一个您只提供键的值。

Immutable.js Map/merge改为使用合并,将商店的状态与响应中的数据组合在一起。

var initialState = Map({ 
    status: true 
}); 

function user(state = initialState, action) { 
    switch (action.type) { 
    case GET_PROFILE: 
    return state.merge(fromJS(action.response)) 
    } 
}) 

你会得到

{ 
    status: true, 
    id: 11, 
    profileImage: "http://www.surfertoday.com/images/stories/addictivesurfing.jpg" 
}