簡體   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