应用 API 响应转换的最佳位置 [英] Best place to apply API response transformation

查看:36
本文介绍了应用 API 响应转换的最佳位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在异步操作创建器中,我从服务器获取数据.对于我的用例,数据的格式不是很好,我需要转换它以在 UI 中使用它.

In an async action creator, I fetch data from the server. The data is not very well formatted for my use case and I need to transform it to use it in the UI.

问题:我应该

  1. 在数据到达后立即转换数据,然后再使用转换后的数据发送成功操作?

  1. Transform data just after it arrives before dispatching a success action with the transformed data ?

fetch("some/url")
.then(res => dispatch(successActionCreator(transform(res)))

  • 使用原始数据发送成功操作并将其存储为,然后将其转换为 mapStateToProps ?

    使用原始数据发送成功操作并在 reducer 中对其进行转换?

    Dispatch a success action with raw data and transform it in the reducer ?

    1.中,数据会在我需要的时候进行转换,在我看来,它把 API 数据格式和我的 Redux 存储解耦了.但是转换逻辑在数据获取动作中.

    In 1., the data will be transformed when I need it, and it seems to me that it decouples the API data format and my Redux store. But the transform logic is in the data fetching action.

    2.中,异步操作创建者保持简单,完全没有逻辑,映射发生在 UI 层.但这意味着我需要使用 reselect 之类的方法优化它,因为每次渲染都会调用 mapStateToProps.

    In 2., the async action creator stays simple with no logic at all and the mapping happens at the UI layer. But it means that I'll need to optimise it with something like reselect since mapStateToProps is called for each render.

    3. 中,异步操作创建器保持简单,完全没有逻辑,但操作与 API 数据格式耦合.

    In 3., the async action creator stays simple with no logic at all but the action is coupled to the API data format.

    我要选择 1.(无论如何都要对转换进行单元测试),但我并不完全满意.有什么建议吗?谢谢!

    I'm going for 1. (and unit-test the transform anyway), but I'm not completely happy. Any suggestion ? Thanks !

    -- 由于这个问题的答案是自以为是,所以我在这里回答我自己.我会选择1.,原因在评论和答案之一中说明.

    -- Edit : since the question is subject to an opinionated answer, I'm kinda answering my self here. I'll go with 1., for all the reasons stated in the comments and one of the answer.

    推荐答案

    选项 1 是正确答案.

    Option 1 is the correct answer.

    如果您传递原始服务器响应,则您将客户端与服务器端实现耦合.隔离这些类型的转换对于应用程序的未来可维护性很重要.

    If you pass around raw server responses you are coupling your client to the server side implementation. Isolating these sorts of transformations is important for the future maintainability of the application.

    这篇关于应用 API 响应转换的最佳位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆