繁体   English   中英

如何修复:“类型错误:无法读取 null 的属性‘打印类型’”

[英]How to fix: "TypeError: Cannot read property 'print-type' of null"

我正在构建一个谷歌图书搜索应用程序,在我开始之前,我打开了检查并在我的控制台上看到

“警告:无法在尚未安装的组件上调用 setState”。

另外,只是为了查看出现的其他错误,我进行了书籍搜索,而我返回的错误说

“类型错误:无法读取 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
    });

"Warning: Can't call setState on a component that is not yet mounted"constructor()setState()的结果。 您需要将其更改为this.state因为您只是在此处定义状态。

我们永远不会在构造函数中编写setState

constructor(props) {
    super(props);
    this.setState({
      "print-type": "all",
      filter: "ebooks"
    });
    this.handleSearch = this.handleSearch.bind(this);
  }

您需要定义状态,

constructor(props) {
    super(props);
    this.state ={
      print_type: "all",   //never write state name like `print-type`, use underscore instead
      filter: "ebooks"
    }
    this.handleSearch = this.handleSearch.bind(this);
  }

每当您要使用print_typethis.state.print_type编写this.state.print_type

对于setState,

this.setState({print_type:printType})

要回答您的主要问题,在React中调用setState是一个很大的否定,因为您尚未定义组件的初始状态 您正在尝试更改未定义的内容。

代替构造函数中的this.setState({...}) ,使用this.state = {...}定义组件的初始状态。 除此之外,您的代码中还有很多其他问题。 但是,您的主要问题是组件的构造函数。 在“挂载”之前调用它。 一旦“挂载”了组件,您就可以使用this.setState({...})来更改组件的状态。

我看到的其他错误或不正确的做法是:

  • 您正在JSON中使用连字符。 不要使用连字符。 使用传统的骆驼壳,即printType

  • 您的变更筛选器功能也不完整,但是您可能知道这一点。

  • e.target.value()无效,因为e.target.value不是函数。 从此开始使用e.target.value

  • 最后,您还需要你的绑定changeFilterchangePrintType功能,您有约束力的相同的方式handleSearch功能。

以我的诚实和谦逊的观点,您可能应该只花20分钟快速浏览一下JavaScript。 我觉得试图在不掌握基础知识的情况下学习一个库将使学习React库比需要的更加困难。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM