javascript - react /通量 : Firing an action from a render method of an component or doing a Rest call from a component?

标签 javascript reactjs redux flux

我的组件上有一个按钮,它将导出对象的 json 以便用户可以下载它?要获取 JSON,我必须进行 REST 调用来获取 JSON,然后我将执行此操作

    var definitionJson = JSON.stringify(definition);
    var definitionName = definition.name
    var exportedFileName = definitionName.concat(".json");
    var file = new Blob([definitionJson], { type: 'application/json' });

    //needed for IE10
    if (window.navigator && window.navigator.msSaveBlob) {
        window.navigator.msSaveBlob(file, exportedFileName);
    }
    else {
        var a = document.createElement("a");
        a.href = URL.createObjectURL(file);
        a.setAttribute("download", exportedFileName);
        a.click();
    }

我有一些问题:-

  1. 我应该如何将其放入 Flux 中?我是否应该触发一个操作创建者来下载 json,然后更新 FileDownload 组件将监听的某个存储。该组件将触发上述代码,但随后它必须在其渲染方法中触发一个操作以将存储值设置为空?
  2. 从组件的渲染方法触发操作是正确的方式吗?
  3. 由于这不会从我的应用程序中传输任何数据,我是否应该使用 React 组件来获取此 JSON 并将其弹出以供下载?这将使组件执行 REST 调用。
  4. 而不是 3,触发一个 Action 创建器来获取 JSON 并将其弹出以供下载?在本例中,我将在操作创建器中编写上述代码。

最佳答案

首先为什么不直接从 API 服务器触发下载?

回答您的问题:

  1. How should I fit this in Flux ? Should I fire an action creator which will download the json and then update some store to which a FileDownload Component will listen to. The component will trigger the above code but then it has to fire an action in its render method to set the store to value to empty?

如果该组件的唯一目的是触发下载,您可能不需要其中的组件。如果以下选项不可用,我可能会在操作创建者回调中处理该问题

  1. Is firing actions from the render method of a component, the right way ?

没有。通常建议您对大多数会影响组件渲染的操作使用 componentWillMount

  1. Since this doesn't flow any data from my application, should I just use the React Component to fetch this JSON and pop it up for download ? This will make component doing a REST call.

我认为这指的是触发从您的 API 服务器的下载?如果是这样我会使用这种方法。 UI 不需要关心如何格式化下载文件。

  1. Instead of 3, Fire an action creator which will fetch the JSON and pop it up for download? In this case I will write the above code inside an action creator.

如果选项 3 可用,那么我认为这样做没有任何优势。只需选择最简单且功能最弱的解决方案即可。

关于javascript - react /通量 : Firing an action from a render method of an component or doing a Rest call from a component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40602394/

相关文章:

javascript - 在 React 中从 Firebase 获取用户对象属性

javascript - jQuery验证错误消息问题

javascript - 关于javascript中的输入名称

reactjs - 如何将 Material UI 步进器中的数字更改为字母表,如 a、b、c、d

javascript - 在 Chrome 扩展中使用动态生成的 anchor 标记

javascript - 如何在元素的单击时将 id 从一个组件传递到另一个组件

javascript - Window Active Directory React JS 自动身份验证

javascript - 如何解构对象以从方法中检索返回值?

javascript - 从函数返回修改后的新对象

javascript - 如何将 Create-React-App 构建推送到 Heroku?