React Native setState 不是函数
React Native setState not a function
谁能解释一下为什么 this.setState 不是函数?
我不明白为什么我的代码有错误
import React from 'react';
import axios from 'axios'
import { StyleSheet, Text, View , Image} from 'react-native';
export default class App extends React.Component {
constructor(){
super();
this.state = {res: []}
}
componentDidMount() {
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then(function (response) {
this.setState({res: response});
}).catch(function (error) {
console.log(error);
});
}
}
谢谢
这是lexical scope
issue. Use arrow function
。
.then((response) => {
this.setState({ res: response });
})
错误的原因是 this
没有引用 axios 的解析器函数中的组件 class 上下文。您可以将解析器函数用作代码的粗箭头函数,如下所示:
componentDidMount() {
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then((response) => {
this.setState({res: response});
}).catch(function(error) {
console.log(error);
});
}
或者您可以将其更改为如下所示:
componentDidMount() {
let self = this;
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then(function(response) {
self.setState({res: response});
}).catch(function(error) {
console.log(error);
});
}
谁能解释一下为什么 this.setState 不是函数?
我不明白为什么我的代码有错误
import React from 'react';
import axios from 'axios'
import { StyleSheet, Text, View , Image} from 'react-native';
export default class App extends React.Component {
constructor(){
super();
this.state = {res: []}
}
componentDidMount() {
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then(function (response) {
this.setState({res: response});
}).catch(function (error) {
console.log(error);
});
}
}
谢谢
这是lexical scope
issue. Use arrow function
。
.then((response) => {
this.setState({ res: response });
})
错误的原因是 this
没有引用 axios 的解析器函数中的组件 class 上下文。您可以将解析器函数用作代码的粗箭头函数,如下所示:
componentDidMount() {
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then((response) => {
this.setState({res: response});
}).catch(function(error) {
console.log(error);
});
}
或者您可以将其更改为如下所示:
componentDidMount() {
let self = this;
axios.get('https://api.github.com/repos/torvalds/linux/commits')
.then(function(response) {
self.setState({res: response});
}).catch(function(error) {
console.log(error);
});
}