【问题标题】:What is the purpose of the flux container function 'createFunctional'?通量容器函数“createFunctional”的目的是什么?
【发布时间】:2017-11-27 23:02:10
【问题描述】:

我正在开发一个具有通量模式的项目,该模式使用通量容器函数“createFunctional”,如下所示:

import {Container} from 'flux/utils';
import View from './MyView.js';
import AppStore from './AppStore.js';

function getStores() {
  return [
    AppStore
  ];
}

function getState() {
  var state = {
    pie: AppStore.getState(),
  };

  return state;
}

export default Container.createFunctional(View, getStores, getState);

我想更好地理解这段代码,但我发现很难找到关于这个函数的文档。

我猜这是以某种方式将 store 和 state 函数绑定到视图,并且它在某种程度上与此代码相同(我已根据 example on the flux website 进行了重组):

class MyView extends Component {
  static getStores() {
    return [AppStore];
  }

  static calculateState(prevState) {
    return {
      pie: AppStore.getState(),
    };
  }

  render() {
    return <div>blah..</div>;
  }
}

const container = Container.create(CounterContainer);

【问题讨论】:

  • 我之前没有使用过纯助焊剂,但查看源代码这似乎类似于 redux 中的connect。我认为它监视商店的变化,当发生变化时,它会将整个状态作为道具传递给底层组件(第一个参数)。

标签: reactjs flux reactjs-flux


【解决方案1】:

查看source code 相当简单。

它创建一个容器组件。该组件订阅所有给定的商店。当商店发生变化时,它会使用getState 函数从他们那里获取任何重要的信息。

getState 的结果然后存储在容器的this.state 中。

容器的render 函数只是渲染View,将整个状态(getState 的结果)作为属性传递给它。

简而言之,容器监视商店中的变化并将它们作为属性传递给视图。这简化了组件的设计,因为它们不必处理状态和订阅商店。

【讨论】:

  • 我真的建议检查来源。有趣的是,flux(或 redux)的实现是多么简单。
  • 你会说我的问题中的两段代码是一样的吗?
  • @OliverWatkins 或多或少,参见github.com/facebook/flux/blob/master/src/container/…createFunctional 的作用几乎相同,但更通用。它允许您传递额外的属性,并且还可以向下传递上下文,这在某些与上下文相关的边缘情况下可能具有一定的重要性。
猜你喜欢
  • 2011-02-16
  • 1970-01-01
  • 2011-08-13
  • 1970-01-01
  • 2017-02-10
  • 2012-01-14
  • 2013-05-22
  • 2012-06-08
  • 1970-01-01
相关资源
最近更新 更多