【问题标题】:Normalizing JSON response from server before updating Redux state在更新 Redux 状态之前规范化来自服务器的 JSON 响应
【发布时间】:2017-08-24 17:24:54
【问题描述】:

服务器对序列化其 JSON 响应保持冷静,因为它不关心哪个客户端正在使用它,这是我(可能是每个人)的首选范例。换句话说,我的 django JSON 有效负载是按照标准以蛇形案例编写的。在此可以更新我的 Redux 存储中的状态之前,应根据 Javascript 标准将键映射到驼峰式大小写。 python 开发人员不认为这是值得的努力,他有一个公平的观点,但不遵循惯例感觉不对。

这个应该怎么处理??

【问题讨论】:

  • 取决于您处理服务器响应的方式,但常见的方式是使用中间件和类似 humps

标签: python django redux json-deserialization


【解决方案1】:

我通常有一个中间件来处理我的所有获取请求,在那里我可以拦截响应并使用 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 },
  },
});

我通常有一个实用程序来处理提取,但这会让您了解如何处理驼峰式转换。

【讨论】:

    【解决方案2】:

    听起来您想要一个特殊的解析器和/或渲染器在骆驼案例和蛇案例之间来回切换。如果您使用Django Rest Framework,您可以使用JSONRenderer 创建一个新的子类,例如CamelCaseJSONRenderer,以便它自动来回切换。

    在基础上,您需要实现一个看起来像这样的函数:

    def to_camelcase(string, lower_first_char=True):
        """Takes snakecase string and converts to camelcase."""
        camelize = ''.join(char.capitalize() for char in word.split('_'))
        result = (camelize[0].lower() + result[1:]) if lower_first else camelize
        return result
    
    def parse(data, lower_first=True):
        """Camelcase the keys of a dictionary or items of a list."""
        if isinstance(data, dict):
            result = {to_camelcase(k): parse(v) for k, v in data.items()}
        elif isinstance(data, list):
            result = [parse(item) for item in data]
        else:
            result = data
        return result
    

    然后您可以在自定义的CamelCaseJSONRenderer 中运行这些函数并将渲染器添加到您的视图中。这样所有的 python 对象在你的 javascript 中都是蛇形的,而骆驼式的。

    【讨论】:

      猜你喜欢
      • 2020-12-10
      • 2019-10-02
      • 2021-05-14
      • 2017-06-14
      • 2016-10-28
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 2016-06-04
      相关资源
      最近更新 更多