简体   繁体   English

this.setState不是函数,本机反应

[英]this.setState is not a function, react-native

It is telling me this.setState' is undefined, but i'm not sure what I can do to make "this" refer to the proper context for setState. 它告诉我this.setState'是未定义的,但是我不确定如何使“ this”引用setState的正确上下文。 I don't know what else I can bind to help. 我不知道还有什么可以帮忙的。

 import React from 'react';
 import { StyleSheet, Text, View } from 'react-native';
 import axios from 'react-native-axios';

 export default class App extends React.Component {
   constructor(props) {
   super(props);
   this.state = {
     data: 50
   }
   this.apirequest = this.apirequest.bind(this);
 }

  componentWillMount() {
    this.apirequest();
  }

  apirequest() { 

    axios.get('http://api.openweathermap.org/data/2.5/weather')
    .then(function (response) {
      console.log(response.data.main.temp);
      this.setState({
         data: response.data.main.temp 
       })
    })
   .catch(function (error) {
     console.log(error);
    });
}

Use arrow function inside the then block to stay in the scope: then块内使用箭头功能保持作用域:

.then(response => {
  this.setState({
     data: response.data.main.temp 
   })
})

Try replacing your function by using a ES6 fat arrow function 尝试使用ES6粗箭头功能替换您的功能

instead of 代替

.then(function (response) {...

do

.then(response => { ...

This works because fat arrow functions do not redefine the definition of this , therefore the value of this is still the originating context 这工作,因为脂肪箭头功能不重新定义this ,因此价值this仍然是起始上下文

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM