由状态反应本征引起的无限循环

时间:2020-05-14 04:15:06

标签: javascript reactjs react-native react-hooks react-native-ios

我试图根据键盘是否打开来显示/隐藏组件。我正在努力理解为什么我最终会经历一个永无止境的循环。这是我的代码:

    const [isKeyboardOpen, setIsKeyboardOpen] = useState(true);

    useEffect(() => {
        Keyboard.addListener("keyboardDidShow", _keyboardDidShow);
        Keyboard.addListener("keyboardDidHide", _keyboardDidHide);

        // cleanup function
        return () => {
            console.log('cleanup')
            Keyboard.removeListener("keyboardDidShow", _keyboardDidShow);
            Keyboard.removeListener("keyboardDidHide", _keyboardDidHide);
        };
    }, []);


    const _keyboardDidShow = () => {
        console.log('opened')
        setIsKeyboardOpen(true);
    };

    const _keyboardDidHide = () => {
        console.log('closed')
        setIsKeyboardOpen(false);

    };

请帮助。

1 个答案:

答案 0 :(得分:0)

我希望这可以解决您的问题

const [isKeyboardOpen, setIsKeyboardOpen] = useState(true);

useEffect(() => {
    Keyboard.addListener("keyboardDidShow", () =>_keyboardDidShow());
    Keyboard.addListener("keyboardDidHide", () =>_keyboardDidHide());

    // cleanup function
    return () => {
        console.log('cleanup')
        Keyboard.removeListener("keyboardDidShow",() => _keyboardDidShow());
        Keyboard.removeListener("keyboardDidHide", () =>_keyboardDidHide());
    };
}, []);


const _keyboardDidShow = () => {
    console.log('opened')
    setIsKeyboardOpen(true);
};

const _keyboardDidHide = () => {
    console.log('closed')
    setIsKeyboardOpen(false);

};