gpt4 book ai didi

javascript - 类型错误 : Cannot read property 'first_name' of undefined on es6 model

转载 作者:行者123 更新时间:2023-12-03 00:36:00 25 4
gpt4 key购买 nike

我想在 es6 模型中设置 JSON API,但收到此错误 类型错误:无法读取未定义的属性“first_name”

JSON API:

{      "type": "user",      "id": 2,      "attributes": {        "username": "madelynn81",        "email": "taylor63@mills.biz",        "first_name": "Emile",        "last_name": "Veum",        "created_at": "2018-11-17 11:48:13"      },      "links": {        "self": "http://test.test/api/v1/user/2"      }    }

es6 model

class UserModel {
constructor(data) {
this.id = data.id;
this.first_name = data.attributes.first_name;
this.last_name = data.attributes.last_name;
this.username = data.attributes.username;
this.email = data.attributes.email;
this.created_at = data.attributes.created_at;
this.link = data.links.self;
}

get getId() {
return this.id;
}

set setId(value) {
this.id = value;
}

get getFirstName() {
return this.first_name;
}

set setFirstName(value) {
this.first_name = value;
}

get getLastName() {
return this.last_name;
}

set setLastName(value) {
this.last_name = value;
}

get getUsername() {
return this.username;
}

set setUsername(value) {
this.username = value;
}

get getEmail() {
return this.email;
}

set setEmail(value) {
this.email = value;
}

get getCreatedAt() {
return this.created_at;
}

set setCreatedAt(value) {
this.created_at = value;
}

get getLink() {
return this.link
}

set setLink(value) {
this.link = value
}
}

我该如何解决这个问题

最佳答案

从您的问题中不清楚您如何使用 getter 来获取值。一个问题:您的设置/获取对应该使用相同的属性名称来命名。它们的命名应与持有该值的属性不同。例如:_id 表示值属性名称,id 表示获取/设置名称。

class UserModel {

constructor(data) {
this._id = data.id;
this._firstName = data.attributes.first_name;
}

get id() {
return this.id;
}

set id(value) {
this._id = value;
}

get firstName() {
return this._firstName;
}

set firstName(value) {
this._firstName = value;
}

}
const data = {
"type": "user",
"id": 2,
"attributes": {
"username": "madelynn81",
"email": "taylor63@mills.biz",
"first_name": "Emile",
"last_name": "Veum",
"created_at": "2018-11-17 11:48:13"
},
"links": {
"self": "http://test.test/api/v1/user/2"
}
}

const user = new UserModel(data);
console.log(user.firstName)

关于javascript - 类型错误 : Cannot read property 'first_name' of undefined on es6 model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53661670/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com