简体   繁体   English

类型错误:无法读取未定义的属性“文本”

[英]TypeError: Cannot read property 'text' of undefined

 constructor() { super() this.state = { privilegesOption: privilegesOption: [{ key: 1, text: "Admin", value: 1 }, { key: 2, text: "Cashier", value: 2 }] } this.foo = this.foo.bind(this) } foo() { let privilegesOut = this.state.privilegesOption.find(e => e.value === 1); console.log(privilegesOut.text) }

Why i keep get this error if i call object property after using.find?如果在 using.find 之后调用对象属性,为什么我会一直收到此错误? if i use this.state.privilegesOption[0].text, its worked如果我使用 this.state.privilegesOption[0].text,它会起作用

A few erros with this which is best answered with some space, I think what you were trying to do was this, I have turned privilegesOption into an array [] containing objects {} where the object key:value pairs are seperated by a comma ,一些错误最好用一些空间来回答,我想你想做的是这个,我把privilegesOption变成了一个数组[]包含对象{}其中对象键:值对由逗号分隔,

this.state = {
    privilegesOption: [
        {
            key: 1,
            text: "Admin",
            value: 1
        },
        {
            key: 2,
            text: "Cashier",
            value: 2
        }
    ]
}

And to find the object where value is 1 you were completely rightfind值为 1 的对象,你是完全正确的

let privilagesOut = this.state.privilegesOption.find(x => x.value == 1)

Your posted code snippet has a syntax error (press "Run code snippet" to see it).您发布的代码片段有语法错误(按“运行代码片段”查看)。 Here is a complete code snippet with fixed syntax errors:这是一个完整的代码片段,其中包含固定的语法错误:

 class Y {} class X extends Y { constructor() { super(); this.state = { privilegesOption: [ { key: 1, text: "Admin", value: 1 }, { key: 2, text: "Cashier", value: 2 } ] }; let privilegesOut = this.state.privilegesOption.find(e => e.value === 1); console.log(privilegesOut.text); } } new X();

It successfully outputs "Admin" on the console.它在控制台上成功输出“Admin”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM