我正在将 lodash/fp 与 React 结合使用,我是 React 的新手。 documentation for _.get()说你可以传递一个默认值:
If the resolved value is undefined, the defaultValue is used in its place.
但是,在签名中没有显示默认值并且将其作为第三个参数传递不起作用,它被忽略了:
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 但没有获得默认值。
最佳答案
如您所见,在您链接的文档中,_.get 的第一个参数是对象本身,而不是字符串。如果您的主要对象是 profile
,那么它应该是第一个参数,第二个参数应该是您想要的路径的字符串。
_.get(profile, 'profile.email')
指的是profile.profile.email
在/fp
中,_.get from lodash/fp doesn’t use defaultValue ,解决方案是使用 getOr,这对我来说效果很好:
关于javascript - 如何调用 lodash/fp get 并使用默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49579238/