首页 > 解决方案 > this.setState 不是函数,react-native

问题描述

它告诉我 this.setState' 是未定义的,但我不确定我能做些什么来使“this”指的是 setState 的正确上下文。我不知道我还能提供什么帮助。

 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);
    });
}

标签: reactjsreact-nativethis

解决方案


使用then块内的箭头功能留在范围内:

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

推荐阅读