【问题标题】:How can I display a nested value in a state array object in React?如何在 React 的状态数组对象中显示嵌套值?
【发布时间】:2020-04-01 16:26:45
【问题描述】:

我是 React 的初学者。我正在尝试将下图中描述的状态对象的"LicType" 属性显示为文本字段的值。

现在 searchJson 是 searchJson:"random text here"

如果 searchJson 没有像那样嵌套,我会使用<TextField value={values.searchJson}/>

如何显示或访问 LicTypenextOfKinaccountNotes 作为文本字段的值?

注意:values 是通过 props 传递的。

编辑

Values.searchJson[0].LicType 产生如下错误

TypeError: Cannot read property 'fname' of undefined

【问题讨论】:

  • 使用searchJson[0].LicType
  • 我试过这个字节仍然出错。 TypeError:无法读取未定义的 EditStudentAccount.render src/components/mainFlow/editStudentAccount/EditStudentInfo.js:97 94 的属性“fname”自动完成 =“fname” 95 |边距=“正常” 96 |变体=“轮廓”样式={{宽度:'100%'}} > 97 |值={values.searchJson[0].fname} | ^ 98 | />网格> 99 | 100 |
  • 请阅读Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers? - 总结是这不是解决志愿者的理想方式,并且可能会适得其反。请不要将此添加到您的问题中。
  • @JuniusL。鉴于紧迫性,我找到了解决方法。我最终将 json 响应分配给仅使用索引而不是整个数组对象的状态。 ``` .then(response=>{this.setState({searchJson:response.data[0]})})``` 而不是.then(response=&gt;{this.setState({searchJson:response.data})})

标签: reactjs state textfield nested-object


【解决方案1】:

鉴于紧迫性,我找到了解决方法。我最终将 json 响应分配给仅使用索引而不是整个数组对象的状态。 .then(response=&gt;{this.setState({searchJson:response.data[0]})}) 而不是 .then(response=&gt;{this.setState({searchJson:response.data})})

【讨论】:

    【解决方案2】:

    您的数组中没有值,因此第一项未定义。您需要先执行空检查:

    const val = searchJson.length && searchJson[0].LicType
    

    或者:

    const val = searchJson.length ? searchJson[0].LicType : ""
    

    当您访问 values.searchJson[0].fname 时也是如此,这是您遇到的错误。

    【讨论】:

    • 但是当我通过浏览器的开发工具查看状态时,它清楚地显示了分配的值,根据问题中所附的图片......
    • 该错误发生在您的 EditStudentInfo.js 文件中,并且与尝试访问未定义对象上的属性 fname 有关。你能把你的那部分代码贴在这里吗?
    • 鉴于紧迫性,我找到了一种解决方法。我最终将 json 响应分配给仅使用索引而不是整个数组对象的状态。 ``` .then(response=>{this.setState({searchJson:response.data[0]})})``` 而不是.then(response=&gt;{this.setState({searchJson:response.data})})
    【解决方案3】:

    searchJson 是数组,所以你通过索引访问:values.searchJson[0].LicType

    【讨论】:

    • 我已经尝试过了,但仍然出现错误。 TypeError:无法读取未定义的 EditStudentAccount.render src/components/mainFlow/editStudentAccount/EditStudentInfo.js:97 94 的属性“fname”自动完成 =“fname” 95 |边距=“正常” 96 |变体=“轮廓”样式={{宽度:'100%'}} > 97 |值={values.searchJson[0].fname} | ^ 98 | />网格> 99 | 100 |
    • 感谢您的提示,它确实有助于找出一种解决方法,我最终将 json 响应分配给仅使用索引而不是整个数组对象的状态。 ``` .then(response=>{this.setState({searchJson:response.data[0]})})``` 而不是.then(response=&gt;{this.setState({searchJson:response.data})})
    猜你喜欢
    • 1970-01-01
    • 2021-12-29
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多