奇怪的 React 钩子行为,无法从函数访问新状态



我使用库react-use-modal,并且我正在尝试读取handleClick函数内部的confirmLoading的更新值。

handleClick确实读取执行const [ confirmLoading, setConfirmLoading ] = useState(false)时定义的confirmLoading的第一个值,但是当i Ineres handleOk中的 setConfirmLoading时,切勿更新。

我不明白我在做什么错

import { Button, Modal as ModalAntd } from 'antd'
import { useModal } from 'react-use-modal'
export interface ModalFormProps {
    form: React.ReactElement
}
export const ModalForm: React.FC = () => {
    const [ confirmLoading, setConfirmLoading ] = useState(false)
    const { showModal, closeModal } = useModal()
    const handleOk = () => {
        setConfirmLoading(true)
        setTimeout(() => {
            setConfirmLoading(false)
            closeModal()
        }, 1000)
    }
    const handleCancel = () => {
        closeModal()
    }
    const handleClick = () => {             
        showModal(({ show }) => (
            <ModalAntd                  
                onCancel={handleCancel}
                onOk={handleOk}
                title='Title'
                visible={show}
            >
                //  the value of confirmLoading is always the one defined 
                //  with useState at the beginning of the file.
                <p>{confirmLoading ? 'yes' : 'no'}</p>                  
            </ModalAntd>
        ))
    }
    return (
        <div>
            <Button onClick={handleClick}>
                Open Modal
            </Button>
        </div>
    )
}

这是由于关闭而发生的。您传递给showModal的组件会记住confirmLoading,当您调用功能setConfirmLoading时,您的组件再次呈现并重新创建功能handleClickshowModal中的"旧" handleClick和"旧"组件对confirmLoading中的新值一无所知。

尝试这样做:

export const ModalForm: React.FC = () => {
    const { showModal, closeModal } = useModal();
    const handleClick = () => {
        showModal(({ show }) => {
            const [ confirmLoading, setConfirmLoading ] = useState(false);
            const handleOk = () => {
                setConfirmLoading(true)
                setTimeout(() => {
                    setConfirmLoading(false)
                    closeModal()
                }, 1000)
            };
            const handleCancel = () => {
                closeModal()
            };
            return (
                <ModalAntd
                    onCancel={handleCancel}
                    onOk={handleOk}
                    title='Title'
                    visible={show}
                >
                    // the value of confirmLoading is always the one defined
                    // with useState at the beginning of the file.
                    <p>{confirmLoading ? 'yes' : 'no'}</p>
                </ModalAntd>
            );
        })
    };
    return (
        <div>
            <Button onClick={handleClick}>
                Open Modal
            </Button>
        </div>
    )
}

相关内容

  • 没有找到相关文章

最新更新