然后保证回调上下文“ this.callFunc()不是函数”

时间:2019-10-03 08:17:42

标签: javascript 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>
        );
    }
}

1 个答案:

答案 0 :(得分:1)

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