在 Flux 应用程序中应该在哪里提出 ajax 请求? [英] Where should ajax request be made in Flux app?

查看:31
本文介绍了在 Flux 应用程序中应该在哪里提出 ajax 请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个具有 Flux 架构的 react.js 应用程序,我正在尝试弄清楚应该在何处以及何时向服务器发出数据请求.有没有这方面的例子.(不是 TODO 应用!)

I'm creating a react.js application with flux architecture and I am trying figure out where and when a request for data from the server should be made. Is there a any example for this. (Not TODO app!)

推荐答案

我非常支持将异步写入操作放在操作创建器中并将异步读取操作放在存储中.目标是将商店状态修改代码保存在完全同步的动作处理程序中;这使得它们易于推理并且易于单元测试.为了防止对同一个端点的多个同时请求(例如,双重读取),我将实际的请求处理移到一个单独的模块中,该模块使用 promise 来防止多个请求;例如:

I'm a big proponent of putting async write operations in the action creators and async read operations in the store. The goal is to keep the store state modification code in fully synchronous action handlers; this makes them simple to reason about and simple to unit test. In order to prevent multiple simultaneous requests to the same endpoint (for example, double-reading), I'll move the actual request processing into a separate module that uses promises to prevent the multiple requests; for example:

class MyResourceDAO {
  get(id) {
    if (!this.promises[id]) {
      this.promises[id] = new Promise((resolve, reject) => {
        // ajax handling here...
      });
    } 
    return this.promises[id];
  }
}

虽然存储中的读取涉及异步函数,但有一个重要的警告,即存储不会在异步处理程序中更新自己,而是触发一个动作,并且在响应时触发一个动作到达.此操作的处理程序最终会进行实际的状态修改.

While reads in the store involve asynchronous functions, there is an important caveat that the stores don't update themselves in the async handlers, but instead fire an action and only fire an action when the response arrives. Handlers for this action end up doing the actual state modification.

例如,一个组件可能会:

For example, a component might do:

getInitialState() {
  return { data: myStore.getSomeData(this.props.id) };
}

商店会实现一个方法,也许是这样的:

The store would have a method implemented, perhaps, something like this:

class Store {
  getSomeData(id) {
    if (!this.cache[id]) {
      MyResurceDAO.get(id).then(this.updateFromServer);
      this.cache[id] = LOADING_TOKEN;
      // LOADING_TOKEN is a unique value of some kind
      // that the component can use to know that the
      // value is not yet available.
    }

    return this.cache[id];
  }

  updateFromServer(response) {
    fluxDispatcher.dispatch({
      type: "DATA_FROM_SERVER",
      payload: {id: response.id, data: response}
    });
  }

  // this handles the "DATA_FROM_SERVER" action
  handleDataFromServer(action) {
    this.cache[action.payload.id] = action.payload.data;
    this.emit("change"); // or whatever you do to re-render your app
  }
}

这篇关于在 Flux 应用程序中应该在哪里提出 ajax 请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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