【问题标题】:lodash solution for input value ={}输入值 ={} 的 lodash 解决方案
【发布时间】:2023-03-12 02:05:01
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs lodash


    【解决方案1】:

    Vanilla JS 有 conditional chaining ?. 语法:

    const userProfile = null
    
    console.log(userProfile?.result?.job)

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多