React-Native中this的带给大家的困惑

转载请标明出处:http://blog.csdn.net/u010046908/article/details/50812572本文出自:【李东的博客】

最近在学习react-native时候,一直会遇到this.setState()或者this.props报如下的错误:

这里写图片描述

问题描述

这是什么原因导致的呢?当时都没有认真的分析该问题的发生点,一直让这个问题困扰我们好几天。
于是,我们想到this的函数是什么呢?估计大家都知道,this代表当前对象,但是this.setState() undefined is not an object错误,提示我们未知的对象,该句话的含义就是我们没有定义该对象。但是this就是当前对象,为什么还会出现如此问题?只有一种可能,就是当前引用的this和this.setState的this不是指向同一个对象,这样才会出想“undefined is not an object”这样的错误。下面用一个例子来简单说明一下:
该例子是一个点击按钮,发送请求获取数据后,更新Text值的例子。

问题的呈现

'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  ToastAndroid,
  View
} from 'react-native';


let format = 2;
let key = 'ad1d20bebafe0668502c8eea5ddd0333';
let cityname='苏州';
import NavButton from './app/util/NavButton';
import Util from './app/util/Util';
import API from './app/api/API';
/**
*健康社区
*/
class HealthSQ extends Component {

    constructor(props){
     super(props);
     this.state={city:'',
                 temperature:''
                };
    }
/**
*获取天气
*/
getWeather(){
   Util.get("http://v.juhe.cn/weather/index?format="+format+"&key="+key+"&cityname="+cityname,function  (ret) {
      this.setState({city:ret.result.today.city,
        temperature:ret.result.today.temperature});
   })
}

  render() {
    return (
      <View style={styles.container}>
         <NavButton
          onPress={this.getWeather.bind(this)}
          text="getfrom"
          style={styles.button1}  />
           <Text>{this.state.city}</Text>
            <Text>{this.state.temperature}</Text>
      </View>
    );
  }
  componentDidMount(){

  }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3CB371',
    height:40,
  },
  welcome: {

    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  button1:{
    width:200,
     // alignItems: 'flex-end',
    alignSelf: 'flex-end',
    // flexDirection:'row',
    marginBottom:200,
    justifyContent:'flex-end',
  },
});

module.exports = HealthSQ;

发送请求成功后,返回响应,从中解析到的数据来更新Text的值。

 this.setState({city:ret.result.today.city,
        temperature:ret.result.today.temperature});

这行代码就是将解析的值设置到state中,更新Text的值,于是直接这样写的话报错:this.setState() undefined is not an object。
这就意味当前的this和this.setState的this不一致。

再看一下发送请求代码:

/**
*获取天气
*/
getWeather(){
   Util.get("http://v.juhe.cn/weather/index?format="+format+"&key="+key+"&cityname="+cityname,function  (ret) {
      this.setState({city:ret.result.today.city,
        temperature:ret.result.today.temperature});
   })
}

其实上面代码中this.setState的this指向的是当前函数对象,因此引用就报错。

要想正确的引用当前类中this,需要将当期的this传入。

/**
*获取天气
*/
getWeather(){
  var thiz = this;
   Util.get("http://v.juhe.cn/weather/index?format="+format+"&key="+key+"&cityname="+cityname,function  (ret) {
     // alert(ret.resultcode+"---"+ret.result.today.city);
      // ret.result.today.city;
      thiz.setState({city:ret.result.today.city,
        temperature:ret.result.today.temperature});
   })
}

重新定义一个thiz,将当前this对象赋值给变量,让其设置 thiz.setState({city:ret.result.today.city,temperature:ret.result.today.temperature});
这样就解决问题。

整体的代码:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  ToastAndroid,
  View
} from 'react-native';


let format = 2;
let key = 'ad1d20bebafe0668502c8eea5ddd0333';
let cityname='苏州';
import NavButton from './app/util/NavButton';
import Util from './app/util/Util';
import API from './app/api/API';
/**
*健康社区
*/
class HealthSQ extends Component {

    constructor(props){
     super(props);
     this.state={city:'',
                 temperature:''
                };
    }
/**
*获取天气
*/
getWeather(){
  var thiz = this;
   Util.get("http://v.juhe.cn/weather/index?format="+format+"&key="+key+"&cityname="+cityname,function  (ret) {
     // alert(ret.resultcode+"---"+ret.result.today.city);
      // ret.result.today.city;
      thiz.setState({city:ret.result.today.city,
        temperature:ret.result.today.temperature});
   })
}

  render() {
    return (
      <View style={styles.container}>
         <NavButton
          onPress={this.getWeather.bind(this)}
          text="getfrom"
          style={styles.button1}  />
           <Text>{this.state.city}</Text>
            <Text>{this.state.temperature}</Text>
      </View>
    );
  }
  componentDidMount(){

  }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#3CB371',
    height:40,
  },
  welcome: {

    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  button1:{
    width:200,
     // alignItems: 'flex-end',
    alignSelf: 'flex-end',
    // flexDirection:'row',
    marginBottom:200,
    justifyContent:'flex-end',
  },
});

module.exports = HealthSQ;

最后来张实现的效果:

这里写图片描述

今天就到这里,欢迎大家反馈意见,一起进步。加油。

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 7
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值