New*_*mer 0 this reactjs 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);
});
}
Run Code Online (Sandbox Code Playgroud)
使用then块内的箭头函数留在范围内:
.then(response => {
this.setState({
data: response.data.main.temp
})
})
Run Code Online (Sandbox Code Playgroud)