【问题标题】:How to return data using ES6 method?如何使用 ES6 方法返回数据?
【发布时间】:2017-10-12 14:24:21
【问题描述】:

我试图使用 ES6 函数返回数据,但它返回的是函数而不是结果。

根据我的代码,结果应该是真或假

我的代码

get_gathereddata_status.js

 export default () => (dispatch, getState) => {
  const { experiment } = getState();
  const { selectedTab, gatherData } = experiment.tabs;
  const { environmentalChanges: { environmentFactor, environmentLocation } } = experiment;
  const { populationChanges: { populationlLocation, populationFactor } } = experiment;
  if (selectedTab === 'tab1') {
    return environmentFactor !== '' && environmentLocation !== '' && !gatherData[selectedTab];
  } else if (selectedTab === 'tab2') {
    return populationlLocation !== '' && populationFactor !== '' && !gatherData[selectedTab];
  }
  return false;
};

ma​​pStateToProps

function mapStateToProps({ experiment }) {
  const { selectedTab } = experiment.tabs;
  const isGatherDataEnabled = gatherDataStatus();
  console.log(isGatherDataEnabled);
  return {
    selectedTab,
    isGatherDataEnabled
  };
}

console.log 在 mapStateToProps 中

ƒ (dispatch, getState) {
    var _getState = getState(),
        experiment = _getState.experiment;

    var _experiment$tabs = experiment.tabs,
        selectedTab = _experiment$tabs.selectedTab,

【问题讨论】:

  • if (selectedTab === 'tab2') { return true; } else if (selectedTab === 'tab2') { return false; } 没有任何意义。这将返回 trueundefined
  • 条件实在是太大了,因为理解我把它简化了
  • 我已经更新了
  • 那么第二个if 正文将永远不会被执行。
  • 对不起,我已经更新了我的代码,这是我的错误

标签: javascript reactjs ecmascript-6 redux


【解决方案1】:

get_gathereddata_status.js 正在返回一个返回另一个函数的函数:

() => (dispatch, getState) => { //...}

所以当你调用它时:

const isGatherDataEnabled = gatherDataStatus(); 
// assuming gatherDataStatus this is the same as get_gathereddata_status.js

isGatherDataEnabled 现在是 gatherDataStatus() 返回的函数,而不是第二个函数的结果。

我想你只是想导出第二个函数:

export default (dispatch, getState) => { //.. }

如果你真的需要,你也可以调用返回的函数:

console.log(isGatherDataEnabled(dispatch, getState));
// You need to call this with the expected arguments. Where do these come from?

【讨论】:

  • 当我尝试这个 Uncaught (in promise) TypeError: getState is not a function
  • get_gathereddata_status.js 返回的第二个函数有两个参数:dispatchgetState。看起来getState 是一个函数。这个功能从哪里来?它没有在您的示例中显示。
  • 嗯。不确定我们是否有足够的信息来修复所有问题,但这就是 console.log() 显示的函数不是真/假值的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-07-26
  • 1970-01-01
  • 2017-07-06
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
  • 2017-07-26
相关资源
最近更新 更多