【问题标题】:null is not an object(evaluating this.state.count)null 不是对象(评估 this.state.count)
【发布时间】:2017-04-03 06:42:39
【问题描述】:

当我尝试为每次按下按钮设置计数时,我遇到了上述错误。

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>

【问题讨论】:

  • 错误提示 this 为 null,或者 this.state 为 null

标签: react-native react-native-android


【解决方案1】:

请这样设置状态

constructor(props){
   super(props);

   this.state = {
      count: 0,
   }
}

然后你可以这样做.state.count

【讨论】:

    【解决方案2】:

    创建 React 类有两种方法: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 */ };
      },
    });
    

    还有一点需要注意的是在构造方法之后没有逗号。

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2021-10-20
      • 2016-06-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多