【问题标题】:Destructuring JavaScript returns an error解构 JavaScript 返回错误
【发布时间】:2020-06-29 17:55:44
【问题描述】:

我有一个函数,我正在尝试从选项中解构几个参数

  fetchArtifactsWithFiltersOG = async options => {
   
    const { nextPage, fromSearch } = options;

  }

问题:

但是,在某些用例中,options are not passed 会抛出 nextPage of undefined error

在这种情况下我如何解构,我不确定选项是否只是有时通过。没有使我的语法 ES5。

【问题讨论】:

  • 为什么不给它们分配默认值?像 const { nextPage = null, fromSearch } = options;然后你可以像 if( nextpage ) { do someting.....} else { do something else }
  • ^ 如果 options 为空怎么办?当它无限期地抛出错误时,这就是我在帖子中所指的。 @parseshyam

标签: javascript ecmascript-6 destructuring


【解决方案1】:

为选项参数设置一个默认值。

async (options = {}) =>

async (options = { nextPage: 1, frontSearch: false }) =>

【讨论】:

    【解决方案2】:

    您可以添加默认值:

    const { nextPage, fromSearch } = options || { nextPage:null, fromSearch:null };
    

    【讨论】:

      【解决方案3】:

      您应该为选项分配一个默认值:

      fetchArtifactsWithFiltersOG = async (options: {}) => {
      
          const { nextPage, fromSearch } = options;
      
      }
      

      fetchArtifactsWithFiltersOG = async options => {
      
          const { nextPage, fromSearch } = options || {};
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-06
        • 2019-03-30
        • 2013-02-24
        • 2011-07-03
        相关资源
        最近更新 更多