Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

javascript - TypeError:无法读取未定义的属性“文本”(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 ?

(如果使用.find后调用对象属性,为什么我总是收到此错误?)

if i use this.state.privilegesOption[0].text, its worked

(如果我使用this.state.privilegesOption [0] .text,它的工作原理)

  ask by Mufid Zukh translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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变成了一个包含对象{}的数组[] ,其中对象的key:value对用逗号分隔,)

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 right

(并find值等于1的对象,那是完全正确的)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...