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

简介: 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/50812572 转载请标明出处:http://blog.
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010046908/article/details/50812572

转载请标明出处: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;

最后来张实现的效果:

这里写图片描述

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

相关文章
|
3月前
|
开发框架 前端开发 JavaScript
探索前端开发中的跨平台框架React Native
本文将介绍前端开发中一种备受关注的跨平台框架React Native,通过比较原生应用与React Native的优缺点,探讨其在实际项目中的应用以及未来发展趋势。
|
3月前
|
开发框架 前端开发 JavaScript
从零开始学习React Native开发
React Native是一种基于React框架的移动端开发框架,使用它可以快速地构建出高性能、原生的移动应用。本文将从零开始,介绍React Native的基础知识和开发流程,帮助读者快速入门React Native开发,并实现一个简单的ToDo应用程序。
|
4月前
|
前端开发 JavaScript Android开发
跨端技术栈综合考察:深入剖析 UniApp、Flutter、Taro 和 React Native 的优势与限制
跨端技术栈综合考察:深入剖析 UniApp、Flutter、Taro 和 React Native 的优势与限制
|
4月前
|
前端开发 安全 Swift
【教程】React Native 应用中的代码混淆与安全性管理
【教程】React Native 应用中的代码混淆与安全性管理
53 0
|
3月前
|
存储 前端开发 JavaScript
从零开始学习React Native开发
【2月更文挑战第1天】React Native是一种跨平台的移动应用程序框架,可以使用JavaScript和React来构建Android和iOS应用程序。本文将带您从零开始学习React Native开发,涵盖了基础知识、组件、样式、布局、API等方面。
|
3月前
|
前端开发 IDE 小程序
【社区每周】React Native 初探;应用中支持添加应用管理员(2月第一期)
【社区每周】React Native 初探;应用中支持添加应用管理员(2月第一期)
34 0
|
4月前
|
移动开发 前端开发 JavaScript
探究移动端混合开发技术:React Native、Weex、Flutter的比较与选择
移动端混合开发技术在移动应用开发领域日益流行,为开发者提供了更高效的跨平台开发方案。本文将比较三种主流混合开发技术:React Native、Weex和Flutter,从性能、生态系统和开发体验等方面进行评估,以帮助开发者在选择适合自己项目的技术时做出明智的决策。
|
4月前
|
移动开发 前端开发 weex
React Native、Weex、Flutter 混合开发技术的比较与选择
移动应用已经成为人们日常生活中不可或缺的一部分,而混合开发技术也随之崛起并逐渐成为主流。本文将比较 React Native、Weex 和 Flutter 三种混合开发技术,并探讨它们各自的优缺点,以及如何根据项目需求做出选择。
60 1
|
4月前
|
开发框架 Dart 前端开发
Flutter vs React Native:跨平台移动应用开发的终极对决
随着移动应用的普及,跨平台移动应用开发成为了一种趋势。Flutter和React Native是当前最受欢迎的跨平台开发框架之一,但它们各自有着不同的特点和优势。本文将对Flutter和React Native进行全方位比较,以帮助开发者了解两个框架的差异,从而选择适合自己的开发工具。
60 3
|
4月前
|
开发框架 前端开发 JavaScript
react native是什么,怎么用
react native是什么,怎么用
45 0