【问题标题】:Uncaught TypeError: Cannot destructure property `name` of 'undefined' or 'null'未捕获的类型错误:无法解构“未定义”或“空”的属性“名称”
【发布时间】:2019-02-18 10:18:28
【问题描述】:

在传递空对象的情况下,对象解构会引发错误

function test ({name= 'empty'}={}) {
  console.log(name)
}
test(null);

未捕获的类型错误:无法解构“未定义”或“空”的属性 name。 测试时 (:1:15) 在:1:1

【问题讨论】:

  • 你有什么问题?
  • 仅当输入参数为undefined 时才分配默认参数。 null 与 undefined 不同。

标签: javascript ecmascript-6 object-destructuring


【解决方案1】:

见docs:

默认函数参数允许在没有传递值或未定义的情况下使用默认值初始化命名参数。

换句话说,如果null 被传递,默认参数将不被赋值:

function fn(arg = 'foo') {
  console.log(arg);
}
fn(null);

改为在函数的第一行进行解构:

function test (arg) {
  const { name = 'empty' } = arg || {};
  console.log(name)
}
test(null);

【讨论】:

  • 可以在函数参数function test (arg = {})中将arg默认为{},而不是const { name = 'empty' } = arg || {};,然后将解构语句const { name = 'empty' } = arg中的|| {}去掉;我个人觉得这更容易阅读,也更简洁。
  • 问题是当null 被传递时默认参数不会触发(见第一个sn-p)。
【解决方案2】:

如果您没有为对象分配任何参数或值,但想将其传递为空,因为您打算在稍后阶段为其分配一个值,最好将其传递为空,不要将其放在括号内.

假设你有:

这个功能:

const {signup}  = useAuth()

这肯定会引发错误,因为您实际上是在不带参数地传递对象。

要解决此问题,您必须从括号中删除空对象,如下所示:

const signup  = useAuth() 

然后在你的类或函数中使用它,如下所示:

async {....
     await signup(emailRef.current.value, passwordRef.current.value)

...}

【讨论】:

    【解决方案3】:
    function test (user = {}) {
      const defaultName= 'Invalid User Object'
      if(!user?.name) return defaultName
      const {name} = user
      return user
    }
    test(null);
    

    【讨论】:

      【解决方案4】:

      这是你需要的:

      function doDotsCalculations(el) {
          const height = el.height();
          const {top = 'empty', left = 'empty'} = el.position() || {};
          const res = height + top + 20;
      
          $(".owl-carousel .owl-dots").css({
              top: `${res}px`,
              left: `${left}px`
          });
      }
      

      【讨论】:

        猜你喜欢
        • 2018-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-06-28
        • 2015-01-06
        • 1970-01-01
        相关资源
        最近更新 更多