null不是一个对象(评估this.state.count)

问题描述:

我正面临上面提到的错误,当我试图为每次按下按钮时设置计数。null不是一个对象(评估this.state.count)

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> 

请设置状态这样

constructor(props){ 
    super(props); 

    this.state = { 
     count: 0, 
    } 
} 

然后你就可以做this.state.count

有做一个阵营类两种方法:ES6和使用React.createClass 。

这两种方法不可互换。您应该在使用ES6类时在构造函数中初始化状态,并在使用React.createClass时定义getInitialState方法。

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 
} 

相当于

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

另外一两件事要注意的是有构造方法之后没有逗号。