如何从商店或服务器获取React Flux中的数据?

时间:2015-12-21 23:10:12

标签: reactjs flux reactjs-flux

对于某些数据调用Flux商店的最佳模式是什么?如果那么将其获取,或者如果服务器则调用服务器?

我在this article的底部看到了这一点,引用了Facebook的Ian Obermiller,但我找不到一个商店的例子,该商店有逻辑与服务器通信时请求的数据是从缓存中丢失。

我想在一个项目中实现这种方法,但我的团队说它打破了Flux模式。有没有人有将添加获取逻辑添加到商店并仅将操作用于写入的经验?

1 个答案:

答案 0 :(得分:0)

当我过去这样做时,模式通常类似于下面的代码。以下是关于该代码的一些注释:

getDataFromAPI()显然是一个HTTP请求或类似的东西,它返回一个promise,它会根据你想要的商店数据来解析。当然,你可以用回调来做到这一点。

storeDataInStore()是对Dispatcher的调用,它负责处理将数据存入商店。

组件侦听商店的更改,因此当您连续调用getDataFromAPI()storeDataInStore()时,组件将听到商店的更改,调用handleStoreDataChange()方法,然后重新启动 - 适当地。

import LoadingComponent from './LoadingComponent';

import Store from '../../stores/ThatStore';
import { getDataFromAPI } from '../../utils/WebUtils';
import { storeDataInStore } from '../../utils/AppUtils';

class ThisComponent extends React.Component {
  constructor() {
    super(props);
  }

  componentWillMount() {
    let dataFromStore = Store.getDataFromStore();
    if (/* condition indicating data is in store */) {
      this.setState(dataFromStore);
    } else if (/* condition indicating data is not in store */) {
      getDataFromAPI().then((data) => {
        storeDataInStore(data);
      });
    }
  }

  componentDidMount() {
    this.handleStoreDataChange = this.handleStoreDataChange.bind(this);
    Store.addChangeListener(this.handleStoreDataChange);
  }

  componentWillUnmount() {
    Store.removeChangeListener(this.handleStoreDataChange);
  }

  handleStoreDataChange() {
    this.setState(Object.assign(Store.getDataFromStore());
  }

  render() {
    if (/* condition indicating that you are awaiting data */) return <LoadingComponent />;
    return (
      /* All of the things you would render if the data is loaded in the store */
    );
  }
}
相关问题