reactjs - 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);
});
}
解决方案
使用then
块内的箭头功能留在范围内:
.then(response => {
this.setState({
data: response.data.main.temp
})
})
推荐阅读
- javascript - 如何在键盘打开时隐藏浮动按钮(Android/iOS)?
- ruby-on-rails - 如何在 Jenkinsfile 中配置 Jenkins 中 Rails 应用程序的测试套件使用的数据库?
- excel - Excel 搜索范围,带回行内容
- html - 控制嵌套网格布局中的图像大小
- c# - 无法链接\导入来自不同文件夹的原始文件
- python - 如何使用内置的 python 模块创建垂直直方图?
- python - Pandas 按条件分组
- variables - 如何在 Qlik Sense 中为具有多个字段的饼图编写变量
- microservices - 播种微服务数据库
- adobe-indesign - GREP 表示文本符号的结尾