2017-08-14 24 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

相关问题