2017-08-14 25 views
0

儘管使用了胖箭頭函數,但在使用setState時綁定了此上下文,我仍然不斷收到此錯誤。任何人都可以幫忙嗎?反應 - 無法讀取未定義的屬性'狀態'

export default class App extends Component { 

constructor(props) { 
    super(props); 
    this.state = { 
     query: '', 
     items: [], 
     repos: [] 
    }; 
} 

search(term) { 
    this.setState({ 
     query: term 
    }); 
    const clientId = '12489b7d9ed4251ebbca'; 
    const secret = 'ff53ac9a93aaa9e7cddc0c009d6f068302866ff2'; 

    function fetchUser() { 
     return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`); 
    } 

    function fetchRepos() { 
     return axios.get(`https://api.github.com/users/${this.state.query}?client_id=${clientId}client_secret=${secret}`); 
    } 

    axios.all([fetchUser(), fetchRepos()]) 
     .then(axios.spread((items, repos) => { 
      this.setState({ 
       items: items.data, 
       repos: repos.data 

      }); 
      console.log(state); 
     })); 

} 
+0

您是否能夠看到發生錯誤的代碼行? – webdeb

+0

它在fetchUser上失敗。我只是添加這個變量。 const query = this.state.query; 謝謝修復它! –

+1

添加到我的答案,你應該使用箭頭函數,因爲他們會重用父'這個' – webdeb

回答

1

從錯誤消息中可以明顯看出this未定義。這可能是因爲您在search()中使用它,並且search()未綁定到組件,使得this完全沒有意義。爲了解決這個問題試着在你的構造函數的末尾添加這一行:

 this.search = this.search.bind(this); 

現在你應該可以在你的搜索功能使用this

0

setState不同步。如果你想在設置它之後使用狀態的值,你必須在對象之後的setState中提供一個回調。

這是我會怎麼做:

onSearch(term) { 
    this.setState({ query: term },() => { 
    console.log(this.state.query); 
    this.search(); 
    }); 
} 

search() { 
    // now you can be sure, that this.state.query is set and use it.. 

    // Use arrow functions, as they will reuse the parent scope. 
    const fetchUser =() => { 

    } 
} 
+2

我寧願將該術語作爲參數傳遞給搜索函數,而不是等待回調。 – Sulthan

+0

也許,如果在UI中不需要這個術語,那麼當然可以忘掉它。在另一方面,有時候你想用OP中的相同參數集(來自狀態)再次執行查詢,在這種情況下,最好有一個方法搜索,這將依賴於狀態。當改變查詢參數時,我們首先應該更新狀態,然後執行搜索。順便說一句,我發現它是有用的演示setState +回調 – webdeb

+0

我正在考慮一些更復雜的搜索表單與標籤/類別等。在React中,每次更改都會有另一個事件處理程序,如'onTags','onCategories','onSearchTerm'。所以你可以在你的狀態更新之後調用一個'search'方法。 – webdeb

0

如果從fetchUser一個錯誤,我認爲你有正確的thissearch功能。所以,你需要綁定fetchUserfetchRepos

const fetchUser =() => { 
     return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`); 
    } 

或者

const fetchUser = function(){ 
     return axios.get(`https://api.github.com/users/${this.state.query}/repos?client_id=${clientId}client_secret=${secret}`); 
    }.bind(this); 

與同爲fetchRepos

+0

@丹尼斯,這個答案有幫助嗎? – Andrew

相關問題