2

几乎所有通量的例子都涉及客户端的数据缓存,但是我认为我无法为我的很多应用程序做到这一点。

在我正在考虑使用 React/Flux 的系统中,单个用户可以拥有我们存储的数千条主要数据(一条记录可能至少有 75 个数据属性)。在客户端缓存这么多数据似乎是个坏主意,并且可能会使事情变得更加复杂。

如果我不使用 Flux,我只会有一个类似 ORM 的系统,它可以与 REST API 对话,在这种情况下userRepository.getById(123),无论我是否在最后一页中请求了该数据,类似的请求总是会命中 API。我的想法是让商店有这些方法。

Flux 是否认为如果我要请求数据,它总是访问 API 并且从不从本地缓存实例中提取数据是不好的?如果大多数数据检索请求总是会遇到 API,我可以使用 Flux 吗?

4

2 回答 2

1

当请求新数据的操作进入时,您可以理智地获得最接近无缓存的方法是将任何存储状态重置为 null 或 []。如果这样做,您必须发出更改事件,否则您会引发竞争条件。

作为 Flux 的替代方案,您可以简单地使用 Promise 和带有 api 的简单 mixin 来修改状态。例如,蓝鸟:

var promiseStateMixin = {
  thenSetState: function(updates, initialUpdates){
    // promisify setState
    var setState = this.setState.bind(this);
    var setStateP = function(changes){
        return new Promise(function(resolve){
            setState(changes, resolve);
        });
    };

    // if we have initial updates, apply them and ensure the state change happens
    return Promise.resolve(initialUpdates ? setStateP(initialUpdates) : null)
      // wait for our main updates to resolve
      .then(Promise.params(updates))
      // apply our unwrapped updates
      .then(function(updates){
          return setStateP(updates);
      }).bind(this); 
  }
};

在您的组件中:

handleRefreshClick: function(){
  this.thenSetState(
      // users is Promise<User[]>
      {users: Api.Users.getAll(), loading: false}, 

      // we can't do our own setState due to unlikely race conditions
      // instead we supply our own here, but don't worry, the
      // getAll request is already running
      // this argument is optional
      {users: [], loading: true}
   ).catch(function(error){
      // the rejection reason for our getUsers promise 
      // `this` is our component instance here
      error.users 
   });
}

当然,这并不妨碍您在应用程序中有意义的时间/地点使用助焊剂。例如,react-router 被用于许多 react 项目中,并且它在内部使用了通量。React 和相关库/模式旨在仅在需要时提供帮助,而从不控制您编写每个组件的方式。

于 2014-12-09T20:55:13.627 回答
0

我认为在这种情况下使用 Flux 的最大优势是你的应用程序的其余部分不必关心数据永远不会被缓存,或者你正在使用特定的 ORM 系统。就您的组件而言,数据存在于存储中,并且可以通过操作更改数据。您的操作或存储可以选择始终使用 API 获取数据或在本地缓存某些部分,但您仍然可以通过封装这种魔力来获胜。

于 2014-12-09T16:36:09.760 回答