在我的React Native应用程序中,我试图从我的API中获取特定的响应字符串,并将其显示在视图中的文本组件中.下面的方法不起作用,并返回“ TypeError:undefined不是函数(正在评估_this5.setState …)
我认为这很简单,但却使我难以理解.
export default class Test extends Component {
constructor (props) {
super(props);
this.state = {
current: 'Blank',
}
}
render () {
return (
<View>
{this.state.current}
</View>
);
}
postRequest (data) {
fetch('https://????/controllers/ajaxController.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: "main=" + parseInt(data),
})
.then(function (response) {
responseData = response.json();
if (response.status == 200) {
return responseData.then((data) => this.setState({ current: data[0] }));
} else {
throw new Error('Server Error!');
}
})
}
}
解决方法:
使用箭头函数可以将此词法范围限定于组件:
postRequest = (data) => {
fetch('https://????/controllers/ajaxController.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
},
body: "main=" + parseInt(data),
})
.then((response) => {
responseData = response.json();
if (response.status == 200) {
return responseData.then((data) => this.setState({ current: data[0] }));
} else {
throw new Error('Server Error!');
}
})
}