【问题标题】:How to fetch data in React Flux from either the store or server?如何从商店或服务器获取 React Flux 中的数据?
【发布时间】:2016-03-28 03:10:46
【问题描述】:

为某些数据调用 Flux 存储并在其存在时获取它或在不存在时调用服务器的最佳模式是什么?

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

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

【问题讨论】:

    标签: reactjs flux reactjs-flux


    【解决方案1】:

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

    getDataFromAPI() 显然是一个 HTTP 请求或类似的返回一个 Promise 的东西,它使用你想要在存储中的数据进行解析。当然,您可以使用回调来做到这一点。

    storeDataInStore() 是对 Dispatcher 的调用,它负责将数据存入存储。

    组件监听 store 上的变化,所以当你连续调用 getDataFromAPI()storeDataInStore() 时,组件会听到 store 上的变化,调用 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 */
        );
      }
    }
    

    【讨论】:

    • hmm.. 使用存储将数据提取/检索与使用该数据的组件分开不是重点吗?
    猜你喜欢
    • 2016-09-16
    • 2017-08-14
    • 2016-02-23
    • 1970-01-01
    • 2015-09-13
    • 2018-09-27
    • 1970-01-01
    • 2016-01-15
    • 2022-11-25
    相关资源
    最近更新 更多