使用箭头功能时,this.setState不是函数

时间:2017-08-05 16:45:12

标签: react-native

console.log打印出正确的数字,但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 个答案:

答案 0 :(得分:6)

尝试使用箭头功能作为自动绑定的承诺

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

  });
}   

答案 1 :(得分:0)

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

let numbers = [1..10]
let numberFilter number = number % 5 = 0 || number % 3 = 0
;;