代码之家  ›  专栏  ›  技术社区  ›  WilliamKF

如何调用lodash/fp get并使用默认值?

  •  6
  • WilliamKF  · 技术社区  · 7 年前

    我正在将lodash/fp与react一起使用,我是react新手。这个 documentation for _.get() 表示可以传递默认值:

    如果解析值未定义,则使用defaultValue替换它。

    但是,在签名不显示defaultValue并且将其作为第三个参数传递不起作用的情况下,它将被忽略:

    import _ from "lodash/fp"
    
    console.log("first:", _.get("email", profile.profile, "test"))
    console.log("second:", _.get("email", profile.profile) ? _.get("email", profile.profile) : "test")
    console.log("third:", profile.profile.email)
    

    我进入控制台:

    app.js:251 first: undefined
    app.js:252 second: test
    app.js:253 Uncaught TypeError: Cannot read property 'email' of undefined
    

    既然它是未定义的,正如“第三个”日志中的错误所示,为什么第一个不给我空字符串而不是未定义的?

    看见 related discussion

    如何调用lodash fp并使用默认值?这就是getOr的目的吗?我尝试了getOr,但没有得到默认值。

    2 回复  |  直到 7 年前
        1
  •  4
  •   CertainPerformance    7 年前

    在链接到的文档中,您可以看到,\u。get是 对象本身 ,而不是字符串。如果您的主要对象是 profile ,则该参数应为第一个参数,第二个参数应为所需路径的字符串。

    _.get(profile, 'profile.email') profile.profile.email

    在里面 /fp ,则, _.get from lodash/fp doesn’t use defaultValue ,解决方案是使用getOr,这对我来说很好:

    https://codesandbox.io/s/vp2opyjkl

        2
  •  3
  •   Gunar Gessner    5 年前

    使用 _.getOr(defaultValue, path, object) 从…起 lodash/fp

    资料来源: