React/Flux:从组件的渲染方法触发动作或从组件执行 Rest 调用?

React/Flux: Firing an action from a render method of an component or doing a Rest call from a component?

我的组件上有一个按钮可以导出对象的 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. 从组件的 render 方法触发动作是否正确?
  3. 由于这不会从我的应用程序中传输任何数据,我是否应该只使用 React 组件来获取此 JSON 并将其弹出以供下载?这将使组件执行 REST 调用。
  4. 而不是 3,触发一个将获取 JSON 并弹出以供下载的动作创建器?在这种情况下,我将在 action creator 中编写上面的代码。

首先,为什么不直接从您的 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 可用,那么我看不出这样做有任何好处。只需选择最简单和最不强大的解决方案。