this.callFunc() is not a function. 该指令在 fetch-6ren">
gpt4 book ai didi

javascript - Promise 然后回调上下文 "this.callFunc() is not a function"

转载 作者:行者123 更新时间:2023-12-02 22:50:06 26 4
gpt4 key购买 nike

我试图在单击按钮时隐藏或显示 React-native 对话框,但我不知道为什么我的代码会生成以下错误:

> this.callFunc() is not a function.

该指令在 fetch.then 回调中执行。

我使用 dialogVisible 变量作为标志来了解对话框是否应该隐藏或显示。

import React, { Component } from 'react';
import { ConfirmDialog } from 'react-native-simple-dialogs';
export default class RegistrationScreen extends Component
{
constructor(props)
{
super(props);
this.state = {
dialogVisible: false,
};
this.callFunc = this.callFunc.bind(this);
}

callFunc = () =>
{
if (this.state.dialogVisible) {
this.setState({ dialogVisible: false });
} else {
this.setState({ dialogVisible: true });
}
};

getRegData()
{
fetch('http://test/api/registration/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: 'Bearer' + ' ' + token,
},
}).then(function (response) {
if (response.status === 204) {
this.callFunc(); // getting error here
} else if (response.status === 200) {
response
.json()
.then(function (object)
{

})
.catch(error =>
{
Alert.alert(error.message);
});
}
});
}

render()
{
let { voucherCode } = this.state;
return (
<View>
<Text onPress={this.getRegData}>
click me
</Text>
<ConfirmDialog
visible={this.state.dialogVisible}
title="Error"
onTouchOutside={() => this.setState({ dialogVisible: false })}
positiveButton={{
title: 'OK',
onPress: () => alert('Ok touched!'),
}}>
<View>
<Image
style={{ height: 40, width: 40, alignSelf: 'center' }}
source={images.success_alert}
/>
</View>
</ConfirmDialog>
</View>
);
}
}

最佳答案

您正在 getRegData() 方法中使用回调,该方法未绑定(bind)到组件实例。以与 this.callFunc 相同的方式绑定(bind)它,或使用箭头函数形式:getRegData = () => {.

关于javascript - Promise 然后回调上下文 "this.callFunc() is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58215013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com