这是我的首选范例(也可能是每个人的范例),即服务器对序列化其 JSON 响应保持冷静,因为它不关心哪个客户端正在使用它。换句话说,我的 django JSON 负载是按照标准以蛇形大小写编写的。在这可以更新我的 Redux 存储中的状态之前,应根据 Javascript 标准将键映射到驼峰式大小写。 python 开发人员认为这不值得付出努力,他说得有道理,但不遵循惯例感觉不对。
这应该怎么处理??
最佳答案
我通常有一个中间件来处理我所有的获取请求,我可以在其中拦截响应并使用 Humps 将键转换为驼峰命名法。
// fetchMiddleware.js
export default ({ dispatch, getState }) => next => (action) => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
const { promise, types, ...rest } = action;
// this middleware expects a promise object in the action,
// the object contains all configurations to send the request to
// the server, if no promise is defined then it just ignores this action
if (!promise) {
return next(action);
}
return fetch(promise.url, promise)
.then(response => Promise.resolve(humps.camelizeKeys(response)))
.then(data => dispatch({ type: types[1], data }))
.catch(error => dispatch({ type: types[2], error }));
}
然后在某些组件或其他任何地方,将像这样分派(dispatch)操作:
store.dispatch({
types: ['BEFORE_REQUEST', 'REQUEST_SUCCESS', 'REQUEST_FAIL'],
promise: {
url: 'some/api.json',
params: { x, y },
},
});
我通常有一个实用程序来处理提取,但这会让您了解如何处理驼峰式转换。
关于python - 在更新 Redux 状态之前规范化来自服务器的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45867631/