React 使用 useRef 在点击事件中获取最新的变量值

React About 758 words

场景

在表单中的input,绑定了useStatehook,但在提交时却获取不到最新的值。

原因

useState是异步更新的,提交事件(函数)在创建时已经渲染完成,所以取到的都是上一次的值。

解决

使用useRef代替useState,在inputonChange事件中赋值ref.current.amount = xxx即可。

export default function Test() {

    const ref = useRef({
        amount: null,
        date: new Date(),
    })

    const onConfirm = () => {
        console.log("amount", ref.current.amount);
        if (!ref.current.amount) {
            Toast.show("请输入金额")
            return;
        }
        httpPost("/accounting/record", ref.current)
            .then(() => {
                Dialog.confirm({
                    title: "操作成功",
                    onConfirm: () => {
                        navigate("/test");
                    }
                })
            })
    };
    
}
Views: 30 · Posted: 2025-12-12

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓
Today In History
Browsing Refresh