我是 Redux 新手,并尝试使用 Immutable.js 对象作为我的存储。我发现自己在处理从服务器获取的数据时不可避免地会使用 fromJS 将 JSON 转换为 Immutable,然后将其转换回 JSON 以发布到服务器。无论潜在的性能成本如何,这都是正确的方法吗?
最佳答案
你说的好像很有道理。使用 Redux 时的典型场景是,您在 thunk 中间件中执行服务器请求,然后使用从服务器收到的数据分派(dispatch)操作。然后您可以将数据转换为 Immutable.js 并将其添加到您的 reducer 中的状态。
简短的伪代码示例:
// Component somewhere
state.dispatch(fetchData());
// Actions
function fetchData() {
function (dispatch, getState) {
// Use something to fetch from server
dispatch({ type: 'FETCH_REQUEST' })
return fetch('/path/to/server')
.then(function (data) {
dispatch({ type: 'FETCH_SUCCESS', data: data })
})
}
}
// Reducer
function reducer(state=Map(), action) {
switch(action.type) {
case 'FETCH_SUCCESS':
// Could also take just a part of the data.
// Could also create things like List, Map
// for specific parts of the data.
return fromJS(action.data)
default:
return state;
}
}
关于javascript - 在与服务器通信时,将 Immutable.js 对象与 JSON 进行相互转换是否很常见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40747032/