【发布时间】:2020-05-29 12:11:56
【问题描述】:
似乎是一个愚蠢的问题,但即使我阅读了错误消息并试图在这里找到此类问题,我也无法找出它发生的原因以及我做错了什么
所以主要目标是将书籍对象添加到库数组中。没有问题,至少现在应该可以正常工作(console.log 显示一切正常),所有文件中的导出和导入都是正确的,我什至在 HiddenPanel.tsx 文件中有 sn-ps 以使用 Library 中的 Library 方法。 ts
错误:TypeError:无法读取未定义的属性“推送” Function.push../src/Library.ts.Library.addBook src/Library.ts:36
第 36 行:
Library.library.push(book)
快速问题描述:一些我无法弄清楚的类型问题。在按下 ADD 后发生(从 Library.class 中的方法调用 push())
文件: 1. HiddenPanel.tsx 2.图书馆.ts
我有一个带有构造函数 (Library.ts) 的 Book 类
class Book {
constructor(public author: string, public title: string, public pages: string, public rating: number) {
title = title
author = author
pages = pages
rating = rating
}
}
书籍构造函数调用方法位于Library类(Library.ts)中
class Library {
static library: Array<object>
library = [
{
author: 'Johann Fjord Kallenberg',
title: 'Norvegian dragonslayers',
pages: '443',
rating: 4
}, {
author: 'Dungo McCallahey',
title: 'Irish Golden Era',
pages: '318',
rating: 3
}, {
author: 'John Doe Mouse',
title: 'Preparing to fight a Wolfgod',
pages: '714',
rating: 4
}
]
public static addBook = (title: string, author: string, pages: string, rating: number) => {
let book = new Book(title, author, pages, rating)
Library.library.push(book)
console.log(Library.library)
}
}
正在从 HiddenPanel.tsx 调用构造函数
class HiddenPanel extends React.Component<Props, State> {
constructor(props: Props) {
super(props)
this.state = {
author: '',
title: '',
pages: '',
rating: 0,
value: '',
}
}
...some private methods here...
private handleClick = () => {
Library.addBook(this.state.author, this.state.title, this.state.pages, this.state.rating)
}
render() {
return(
<div className="add-book-section">
...some stuff here...
<div onClick={this.handleClick} className="submit">ADD</div>
</div>
)
}
}
【问题讨论】:
-
在你的类定义中你需要实例化库来初始化类成员库,这就是它未定义的原因...
library = [] -
@AshwynHorton 你能告诉我我应该在哪里做吗?我已经在 Library 类中初始化了库,我试图用一个空数组(library = [])来做,现在看来我不明白(静态库:Array
-
大声笑,我将库:Array
标签: arrays reactjs typescript