首页 > 解决方案 > Reactjs:为什么我的 Android 虚拟设备显示“this.setState_if_Tie”不是一个函数?

问题描述

我正在尝试使用 react-native 在我的移动应用程序中制作井字游戏功能。但是当用户赢得游戏时,游戏并没有停止这一轮,而是继续游戏,直到每个插槽都被填满并弹出一个错误说'this.setState_if_Tie不是函数'。

另一方面,当结果为平局时,屏幕将冻结为白色。

以下是与上述问题相关的一些代码:

    judgeWinner(inputs){    //check the winning situation based on 'const conditions'
        return conditions.some(d => d.every(item => inputs.indexOf(item) !== -1));
    }

    //if result === -1  game continue , result === 0 user won
    //if result === 1  bot won , result === 2 no winner

    setstate_if_Win(parse_res, parse_result){
        if (parse_res && parse_result !== 0){
            this.setState({ result: 0});   //User win
        }
        if (parse_res && parse_result !== 1) {
            this.setState({ result: 1});  //Bot win
        }
    }

    setstate_if_Tie = () => {
        this.setState({ result: 2 });
    }

    componentDidUpdate() {
        const { userInputs , botInputs , result} = this.state;
        const inputs = userInputs.concat(botInputs);

        //res is result
        if (inputs.length >= 5) {
            let res = this.judgeWinner(userInputs);  // go to line 95 to check winning result for user
            if (res && result !== 0) {
                this.setstate_if_Win(res, result);   //User win
                return;
            }
            res = this.judgeWinner(botInputs);  // go to line 95 to check winning result for bot
            if (res && result !== 1) {
                this.setstate_if_Win(res, result);  //Bot win
                return;
            }
        }
        if (inputs.length >= 9 && result !== 2) {
            this.setState_if_Tie();    //No winner (Tie)
        }
    }

有什么办法可以解决这个问题吗?先感谢您。

标签: javascriptreactjsreact-native

解决方案


您必须命名 setState_if_Tie 而不是 setstate_if_Tie:

setstate_if_Tie = () => {
    this.setState({ result: 2 });
}

推荐阅读