javascript - 如何解决:“TypeError:无法读取 null 的属性‘打印类型’”
问题描述
我正在构建一个谷歌图书搜索应用程序,甚至在我开始之前我打开检查并在我的控制台上看到
“警告:无法在尚未安装的组件上调用 setState”。
另外,只是为了看看出现了哪些其他错误,我进行了书籍搜索,而我回来的错误说
“TypeError:无法读取 null 的属性‘打印类型’”。并且控制台将这行代码指向为问题“this.state[”print-type“]”
我是新来的反应,所以现在我是所有的拇指我需要在我的处理程序中放置一个 componentDidMount 还是我需要进一步绑定这个处理程序才能让它工作?
在我的构造函数中,我插入this.handleSearch = this.handleSearch.bind(this)
了认为这将解决我的问题
“无法在尚未安装的组件上调用 setState。”
但这没有用。
constructor(props) {
super(props);
this.setState({
"print-type": "all",
filter: "ebooks"
});
this.handleSearch = this.handleSearch.bind(this);
}
changeFilter(e) {
const filter = e.target.value();
this.setState({
filter
});
}
changePrintType(e) {
const printType = e.target.value();
this.setState({
"print-type": printType
});
}
handleSearch(q) {
console.log(this.state);
const key = "AIzaSyAJ448LHnJ0N6XxzOyIRfhJFveQzwHU_Ms";
const baseurl = "https://www.googleapis.com/books/v1/volumes";
const url = `${baseurl}?q=${encodeURIComponent(q)}&key=${key}&print-type=${
this.state["print-type"]
}&filter=${this.state.filter}`;
const options = {
headers: {
"Content-Type": "application/json"
}
};
我希望看到所有我搜索的同名书籍。
解决方案
初始化状态的正确方法是 -
this.state = {
print-type: "all",
filter: "ebooks"
};
设置状态的正确方法是 -
this.setState({
print-type: printType
});
推荐阅读
- javascript - 如何过滤剑道网格(AngularJs)中的对象数组?
- authentication - JWT 不解码
- c# - 将选定的 TextAsset 分配给新的 TextAsset 变量(Unity、C#)
- swiftui - SwiftUI 如何让 ForEach 循环根据 Picker 中选定月份的天数进行迭代
- javascript - 带有 d3.js 的圆圈内的点
- java - 现在哪种 JWT + Spring Security 配置方法是相关的?
- ios - SwiftUI - 在作为列表一部分的切换开关下添加描述
- github - 与 GIT 的雪花连接
- html - 如何将底部菜单重叠在图像顶部并将其居中?
- xero-api - 您如何开始使用新的 Xero API 应用程序?当我登录到 myapps 区域时,我得到一个带有三个闪烁点的空白屏幕