如何将这两个函数组合成一个带有两个参数的函数?

时间:2018-06-04 07:18:41

标签: react-native this bind

我有两个功能:

setCallModalFalse = (incomingFlag) => () => {
        if (incomingFlag === 'EmergencyCall') {
            this.setState({ callModal: false });
            this.props.navigation.navigate('EmergencyCall'); 
        } else {
            loggingService.debug('we are not going anywhere');
            this.setState({ callModal: false });
        }
    }
setBeepModalFalse = (incomingFlag) => () => {
            if (incomingFlag === 'PoliceIconPage') {
                this.setState({ beepModal: false });
                this.props.navigation.navigate('PoliceIconPage');
            } else {
                loggingService.debug('hey you pressed setbeepmodalfalse');
                this.setState({ beepModal: false });
            }

我试图将它们合并为一个功能

handleModalAndNavigation = (whichModal, incomingFlag) => () => {
    if (whichModal === 'beep' && incomingFlag === 'PoliceIconPage') {
        this.setState({ beepModal: false });
        this.props.navigation.navigate('PoliceIconPage'); 
    } else {
        this.setState({ beepModal: false });
    }
    if (whichModal === 'call' && incomingFlag === 'EmergencyCall') {
        this.setState({ callModal: false });
        this.props.navigation.navigate('EmergencyCall'); 
    } else {
        this.setState({ callModal: false });
    }
}

我的构造函数如下所示:

constructor(props) {
        super(props);
        this.setBeepModalFalse = this.setBeepModalFalse.bind(this);
        this.setCallModalFalse = this.setCallModalFalse.bind(this);
        this.callButton = this.callButton.bind(this);
        this.alarmButton = this.alarmButton.bind(this);
        this.handleModalAndNavigation = this.handleModalAndNavigation.bind(this);
        this.state = {
            callModal: false,
            beepModal: false,

        };
        this.batteryLevelIndicator = '';
    }

然而,当我尝试加载它时,我收到错误" TypeError:无法读取属性' bind'未定义'"

使用setCallModalFalse和setBeepModalFalse时没有任何问题。
为什么我的功能突然未定义?

1 个答案:

答案 0 :(得分:1)

您需要在构造函数中删除绑定函数声明//this.handleModalAndNavigation = this.handleModalAndNavigation.bind(this);,因为您在声明函数时已经使用了ES6语法。

你的函数声明应该是这样的,

handleModalAndNavigation = (whichModal, incomingFlag) => {
    if (whichModal === 'beep' && incomingFlag === 'PoliceIconPage') {
        this.setState({ beepModal: false });
        this.props.navigation.navigate('PoliceIconPage'); 
    } else {
        this.setState({ beepModal: false });
    }

    if (whichModal === 'call' && incomingFlag === 'EmergencyCall') {
        this.setState({ callModal: false });
        this.props.navigation.navigate('EmergencyCall'); 
    } else {
        this.setState({ callModal: false });
    }
}