React-Native 踩坑第二弹-undefined is not a function(evaluating 'this.setState(...))

先看报错的代码

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  Image,
  View
} from 'react-native';

import MyScene from "./MyScene"
import Logo from "./node_a/Logo"
import Home from "./node_a/Home"

export default class BaZi extends Component {
  constructor(props){
      super(props);
      this.state = {isLogo: true};
  }
  jumpToHome(){
      console.log("jumptohome :");
      this.setState({isLogo:false});
  }
  render() {
    console.log("render :"+JSON.stringify(this.state));
      if (this.state.isLogo) {
        return ;
      }else{
        return ;
      }
  }

}

AppRegistry.registerComponent('bazi', () => BaZi);

这段代码的作用比较容易明白。
先显示一个Logo页面,Logo里使用setTimeout触发一个onTimeOut事件。
(见我的 第一个坑的文章 http://www.jianshu.com/p/f688377e6a6a)
onTimeOut调用本地的jumpToHome
JumpToHome修改state,使得显示一个Home出来。

但这个看起来没问题的代码,报错了。

错误解决

React-Native 踩坑第二弹-undefined is not a function(evaluating 'this.setState(...))_第1张图片
Screenshot_20170122-112133.png

使用console.log(this)打印出来发现是空的。。。。

我似乎明白点什么了。。。网上找了个代码

this.jumpToHome = this.jumpToHome.bind(this);

放到constructor中。

...我真想吐个槽。。用一个this真的有必要绑一下吗???!!!!

另一种写法

当然我对上述代码又做了点优化

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  Image,
  View
} from 'react-native';

import MyScene from "./MyScene"
import Logo from "./node_a/Logo"
import Home from "./node_a/Home"

export default class BaZi extends Component {
  constructor(props){
      super(props);
      this.state = {isLogo: true};
  }
  render() {
      if (this.state.isLogo) {
        return {this.setState({isLogo:false});}}/>;
      }else{
        return ;
      }
  }

}

AppRegistry.registerComponent('bazi', () => BaZi);

用lambda表达式的写法,不用绑定!!!

有一种写法

{this.jumpToHome.bind(this)}/>;

这种写法似乎比较常见!
比如

    render() {
        return (
            
                
                    Push Plain Screen
                

                
                    Push Styled Screen
                

                
                    Show Modal Screen
                

                {
                    Platform.OS === 'ios' ?
                        
                            Show LightBox
                         : false
                }

                {
                    Platform.OS === 'ios' ?
                        
                            Show In-App Notification
                         : false
                }

                
                    Show Single Screen App
                
            
        );
    }

你可能感兴趣的:(React-Native 踩坑第二弹-undefined is not a function(evaluating 'this.setState(...)))