2016-05-13 38 views
0

在onclick函數下面的代碼中,testNewBug無法訪問其父組件「BugList」的狀態。任何人都可以看到我在哪裏出錯了,我正確地設置了狀態,並可以在DevTools中查看它,當然組件中的函數'this.state'應該工作嗎?React JS - 組件內部的功能無法看到狀態

class BugList extends React.Component { 

    constructor() { 
    super(); 
    this.state = { 
     bugs: bugData 
    } 
    } 

    render() { 
    console.log("Rendering bug list, num items:", this.state.bugs.length); 
    return (
     <div> 
     <h1>Bug Tracker</h1> 
     <BugTable bugs={this.state.bugs} /> 
     <button onClick={this.testNewBug}>Add Bug</button> 
     </div> 
    ) 
    } 

    testNewBug() { 
     var nextId = this.state.bugs.length + 1; 
     this.addBug({id: nextId, priority: 'P2', status:'New', owner:'Pieta', title:'Warning on console'}) 
    } 

    addBug(bug) { 
     console.log("Adding bug:", bug); 
     // We're advised not to modify the state, it's immutable. So, make a copy. 
     var bugsModified = this.state.bugs.slice(); 
     bugsModified.push(bug); 
     this.setState({bugs: bugsModified}); 
    } 

} 

回答

0

哦,親愛的,我是白癡,我忘了我的事件處理程序綁定到「這」

<button onClick={this.testNewBug.bind(this)}>Add Bug</button> 
0

,如果你知道該方法將總是綁定到當前的類實例,你總是可以定義你的方法是這樣用=>

testNewBug =() => { 
     var nextId = this.state.bugs.length + 1; 
     this.addBug({id: nextId, priority: 'P2', status:'New', owner:'Pieta', title:'Warning on console'}) 
    } 

你將不必擔心bind(this)所有的地方,這保證了函數有一個實例p呃類。

相關問題