2017-08-05 96 views
0

console.log会打印出正确的数字,但this.setState会引发错误。我以为我用箭头函数正确地绑定了它。使用箭头功能时,this.setState不是函数

export default class App extends React.Component { 

constructor(props) { 
    super(props); 
    this.emotion='happy'; 
    this.state = { 
     idList:[] 
    }; 
} 

componentWillMount() { 
this.getEmotionIDs(); 
} 


getEmotionIDs =() => { 
    firebase.database().ref(this.emotion).once('value').then(function(snapshot) { 
     console.log("IDs: " + snapshot.val()); 
    this.setState({ idList: snapshot.val()}); 

    }); 
} 


render() { 

    return (
.... 
) 

回答

2

尝试使用箭头功能,为您承诺的自动捆绑

getEmotionIDs =() => { 
    firebase.database().ref(this.emotion).once('value').then((snapshot) => { 
     console.log("IDs: " + snapshot.val()); 
    this.setState({ idList: snapshot.val()}); 

    }); 
} 
+1

优秀...那么做了....非常感谢 – Allen

+0

'这'是最难的部分在JavaScript中,我仍然遇到麻烦。希望你通过提问来掌握它。 –

0

getEmotionIDs需要bind太:

getEmotionIDs =() => { 
firebase.database().ref(this.emotion).once('value').then(function(snapshot) { 
    console.log("IDs: " + snapshot.val()); 
    this.setState({ idList: snapshot.val()}); 

    }).bind(this); 
} 
+0

好,我试过了,并不断收到错误可能未处理Promise Rejection(id:0): TypeError:this.setState不是函数。 (在'this.setState({idList:snapshot.val()})','this.setState'是undefined) – Allen