我通常有一个中间件来处理我的所有获取请求,在那里我可以拦截响应并使用 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 }));
}
然后在某个组件或其他任何地方,操作将像这样被调度:
store.dispatch({
types: ['BEFORE_REQUEST', 'REQUEST_SUCCESS', 'REQUEST_FAIL'],
promise: {
url: 'some/api.json',
params: { x, y },
},
});
我通常有一个实用程序来处理提取,但这会让您了解如何处理驼峰式转换。