Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

null is not an object(evaluating this.state.count)

I am facing the above mentioned error when i am trying to set a count for everytime the button is pressed.

export default class ViewIdeas extends Component{
get InitialState(){
  return {
  count : 0
  }
}
render(){
    return(
   .......
 <Button transparent>
             <Icon name='ios-thumbs-up-outline' style={{fontSize:21}} 
              onPress={() => this.setState({count: ++this.state.count})}/>
              <Text>{'Like' + this.state.count}</Text>
    </Button>
like image 966
Avikrit Khati Avatar asked Apr 03 '17 06:04

Avikrit Khati


2 Answers

Please set state like this

constructor(props){
   super(props);

   this.state = {
      count: 0,
   }
}

And then you can do this.state.count

like image 75
Suhail Mehta Avatar answered Nov 17 '22 10:11

Suhail Mehta


There are two approaches to make a React class : ES6 and by using React.createClass.

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  } // Note that there is no comma after the method completion
}

is equivalent to

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

Also one more thing to note would be there are no commas after the constructor method.

like image 34
atitpatel Avatar answered Nov 17 '22 09:11

atitpatel