首页 > 解决方案 > 如何解决:“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"
      }
    };

我希望看到所有我搜索的同名书籍。

标签: javascriptreactjs

解决方案


初始化状态的正确方法是 -

this.state = {
      print-type: "all",
      filter: "ebooks"
    };

设置状态的正确方法是 -

this.setState({
      print-type: printType
    });

推荐阅读