1

I have trouble with arrow functions in react native. When I write an arrow function, I get an error saying

this.setstate is not a function

but when I write a regular function , I do not get any errors. Can someone tell me where is the problem. My code is below

var Register = React.createClass({

getInitialState : function(){

return {
ad:'',
soyad:'',
mail: '',
gcm_id:'',

},
componentWillMount: function() {
this.get_db();
},
get_db: async ()=> {     
this.setState({ mail: 'adadsasd' });    

},

})
Vahe Tshitoyan
  • 1,439
  • 1
  • 11
  • 21
  • Because if you write it as a regular function, React autobinds `this` for you. But since you use an arrow function that does not bind `this`, React cannot autobind `this` to refer to your component instance. – Andrew Li Jun 22 '17 at 23:07
  • so how should i write arrow function ? – user8202387 Jun 22 '17 at 23:09
  • Don't use an arrow function, use a regular function. – Andrew Li Jun 22 '17 at 23:10
  • thanks for answer andrew – user8202387 Jun 22 '17 at 23:16
  • 1
    Possible duplicate of [React Native: this.setState is not a function](https://stackoverflow.com/questions/38440925/react-native-this-setstate-is-not-a-function) – Vahe Tshitoyan Jun 23 '17 at 00:32
  • use an es6 class and it will work, the newer versions deprecated createClass anyways so you wont be able to upgrade unless you refactor – Matt Aft Jun 23 '17 at 00:46
  • @VaheTshitoyan This has nothing to do with that. That's with ES6 classes that don't have React autobinding. This is an ES5 component that has autobinding, but since arrow functions don't bind their own `this`, autobinding doesn't work thus `this` actually refers to `window`. – Andrew Li Jun 27 '17 at 18:45

0 Answers0