Wil*_*mKF 6 javascript lodash reactjs
我正在将 lodash/fp 与 react 一起使用,并且是新来的反应。_.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)
Run Code Online (Sandbox Code Playgroud)
我进入控制台:
app.js:251 first: undefined
app.js:252 second: test
app.js:253 Uncaught TypeError: Cannot read property 'email' of undefined
Run Code Online (Sandbox Code Playgroud)
由于在“第三个”日志中看到错误是未定义的,为什么第一个不给我空字符串而不是未定义?
见相关讨论。
如何调用 lodash fp 并使用默认值?这是 getOr 的用途吗?我尝试了 getOr 并且没有获得默认值。
在您链接到的文档中,如您所见, _.get 的第一个参数是对象本身,而不是字符串。如果您的主要对象是profile,那么它应该是第一个参数,第二个参数应该是您想要的路径的字符串。
_.get(profile, \'profile.email\')指的是profile.profile.email
在 中/fp,来自 lodash/fp 的 _.get 不\xe2\x80\x99t 使用 defaultValue,解决方案是使用 getOr ,这对我来说效果很好:
https://codesandbox.io/s/vp2opyjkl
\n| 归档时间: |
|
| 查看次数: |
5846 次 |
| 最近记录: |