【问题标题】:How to refactor those quite similar arrow functions? [closed]如何重构那些非常相似的箭头函数? [关闭]
【发布时间】:2019-09-05 21:07:40
【问题描述】:

我正在重构一个 react 文件中的一些代码,我有两个函数几乎做同样的事情......但一个返回一个函数,另一个执行一些代码。

我现在不太擅长 ES6 和箭头函数。而且我不明白如何重构它。

 switchEventSelectedSchedule = cb => option => {
    this.setState(
      // Mutate the state
      () => ({
        eventSelected: option.id,
        isLoading: true
      }),
      // Callback to fire when the state has been mutated with the new event id
      async () => {
        await this.longPollingAllMatches();
        this.setState(() => ({
          isLoading: false
        }));
        const { currentRoundId, rounds } = this.state;
        cb(rounds, currentRoundId);
      }
    );
  };

  switchEventSelectedRoundTable = option => {
    this.setState(
      // Mutate the state
      () => ({
        eventSelected: option.id,
        isLoading: true
      }),
      // Callback to fire when the state has been mutated with the new event id
      async () => {
        await this.longPollingAllMatches();
        this.setState(() => ({
          isLoading: false
        }));
      }
    );
  };

在一种情况下(想象一下 if(schedule))我需要返回 cb 函数,否则我必须执行其余代码。

抱歉似乎很愚蠢,但我认为我误解了 ES6 语法中的某些内容来实现这一点......

非常感谢!

【问题讨论】:

  • 你可以在这里尝试使用 Babel 将你的 ES6 转换为 ES5:babeljs.io/repl
  • 我不认为人们可以在不进行重大猜测的情况下帮助您,因为您没有解释当前代码应该完成什么或显示调用上下文或解释您的重构目标是什么。我个人鄙视 switchEventSelectedSchedule = cb => option => {} 这样的代码结构,因为它很难阅读,我们需要查看调用上下文才能了解它是如何使用的。
  • @jfriend00 我的回答是否遗漏了什么?不知道为什么这个问题会得到“不清楚”的近距离投票。
  • @Bergi - 好吧,我们中的几个人都不清楚这个问题,我仍然不明白这个问题是如何导致你的答案的。所以,即使有人认为他们理解这个问题(你)给我一个答案,我仍然不理解这个问题。对我来说,这是一个不清楚的问题。 “不清楚”在旁观者的眼中,所以我想你理解它的荣誉。我还不清楚。
  • @jfriend00 我知道 OP 想要重构这个工作代码,确实认识到代码重复,但不知道如何解决它。但可以肯定的是,清晰度是一种主观衡量标准:-)

标签: javascript ecmascript-6 arrow-functions


【解决方案1】:

只需让switchEventSelectedRoundTable 使用不执行任何操作的回调调用另一个函数。由于switchEventSelectedSchedulecurried,这很简单:

switchEventSelectedRoundTable = switchEventSelectedSchedule((rounds, currentRoundId) => {});

【讨论】:

  • 对我帮助很大!!! :) 非常感谢!
猜你喜欢
  • 1970-01-01
  • 2020-02-20
  • 1970-01-01
  • 1970-01-01
  • 2018-02-07
  • 1970-01-01
  • 2018-06-29
  • 2021-12-11
  • 2019-07-21
相关资源
最近更新 更多