簡體   English   中英

反應錯誤 - 無法讀取未定義的屬性“setState”

[英]React error - Cannot read property 'setState' of undefined

下面的代碼為我返回一個錯誤 Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

我是新來的反應,這似乎非常基本。 任何建議我可能做錯了什么。 從 json 結果我想將所有名稱存儲在我的數組中。

import React, { Component } from "react";

class Search extends Component {
  constructor(props) {
  super(props);
  this.state = {
    list: [],
  }
}

Search() {

  fetch("http://url/getSearchResults")
    .then(res => res.json())
    .then(
      (res) => {

        this.setState({
          list: res.data.name
     })
  })
}

這是 React 中類的一個非常常見的問題——有兩種方法可以解決這個問題:

  1. 在構造函數中綁定你的方法:
constructor(props) {
  super(props);

  this.state = {
    list: [],
  }

  this.Search = this.Search.bind(this);
}
  1. 改用箭頭函數:
search = () => { ... }

有關更多信息,請參閱此帖子

:使用componentDidMount()如果你正在努力讓自己在安裝取通話將是有益的-上面的地址問題的答案this被未定義按照您所看到的錯誤。

componentDidMount()添加到Search() ,在安裝組件(插入到樹中)后立即調用它。 需要 DOM 節點的初始化應該放在這里。它是從遠程端點加載數據的好地方。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM