【问题标题】:Is there a way to avoid this repetition in React Js有没有办法避免 React Js 中的这种重复
【发布时间】:2022-11-16 01:43:55
【问题描述】:

编写此函数而不重复某些值并且只添加所需值的最佳方法是什么初始文本

createThread = () => {
    if (this.props.first) {
        publishLow = window.google.createPublish({
            readId : this.props.readId
        });
    } else {
        publishLow = window.google.createPublish({
            readId : this.props.readId,
            // The value needed in this condition
            initialText : this.props.initialText
        });
    }
};

【问题讨论】:

  • 就我个人而言,我会保持原样。它使其更具可读性和可测试性。

标签: javascript reactjs


【解决方案1】:

好吧,你可以这样重构,以避免重复

createThread = () => {
    const { readId, first, initialText } = this.props;
    const payload = { readId };
    if (!first) payload.initialText = initialText;
    publishLow = window.google.createPublish(payload);
}

还添加了对象解构以使代码更具可读性。

【讨论】:

    【解决方案2】:

    我同意安迪的观点,但如果你想让它变小,这是我的想法:

    createThread = () => {
        const arg = {
                readId : this.props.readId
        };
        if (!this.props.first) {
            arg["initialText"] = this.props.initialText;
        }
    
        publishLow = window.google.createPublish(arg);
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-15
      • 1970-01-01
      • 2020-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      相关资源
      最近更新 更多