输入值 ={} 的 lodash 解决方案

lodash solution for input value ={}

我有一个带有一些输入字段的表单,我需要从服务器获取一个 JSON,然后从该 JSON 对象中获取输入默认值,但有时该对象可能为空,因为网络问题,在这种时候我得到错误值不能为空, 我需要一种方法来使用 Lodash 来处理这个问题,有人可以帮我吗? 请告诉我如何将它传递给 value={}

下面是不使用 Lodash 的示例,我想去掉代码中的所有 &&s

<Input value={userProfile && userProfile.result.job} onChange={() => setJob(...userProfile.result.job)}  />

Vanilla JS 具有 conditional chaining ?. 语法:

const userProfile = null

console.log(userProfile?.result?.job)

如果不支持条件链,可以使用lodash的_.get():

const userProfile = null

console.log(_.get(userProfile, 'result.job'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>