V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
realJamespond
V2EX  ›  React

set_state 嵌套写法有没有问题?

  •  
  •   realJamespond · 348 天前 · 897 次点击
    这是一个创建于 348 天前的主题,其中的信息可能已经有所发展或是发生改变。

    切 tab 时想做一个表单验证,antd 的表单验证是异步的,不想用一个 ref 保留之前的 activeKey ,就想到这种写法,不知是否可行,目前看 OK

            <Tabs type="card" activeKey={activeKey} onChange={(key: string) => {
              set_activeKey(prev=>{ 
                if (prev === '1') {
                  form.validateFields().then(()=>{
                    console.debug('validateFields ok')
                    set_activeKey(key as Key)
                  })
                  console.debug('return prev')
                  return prev
                } else {
                  return key as Key
                } 
              })
            }}>
    
    2 条回复    2023-05-16 16:36:34 +08:00
    yandif
        1
    yandif  
       347 天前   ❤️ 1
    是可以的,form.validateFields() 是一个异步,不会阻塞 return prev;

    所以是先执行了外层的 set_activeKey 。然后等表单校验完成,如果表单验证通过,执行 .then 中的函数。切换 tab 页。

    控制台应该先打印 "return prev", 然后验证通过打印 "validateFields ok"

    不过我没看懂 ”不想用一个 ref 保留之前的 activeKey “ 是啥意思?

    不能直接用 activeKey 吗?

    ```tsx
    <Tabs
    type="card"
    activeKey={activeKey}
    onChange={(key: string) => {
    if (activeKey === "1") {
    form.validateFields().then(() => {
    console.debug("validateFields ok");
    set_activeKey(key as Key);
    });
    } else {
    set_activeKey(key as Key);
    }
    }}
    ></Tabs>
    ```
    realJamespond
        2
    realJamespond  
    OP
       347 天前
    感谢回复,===不想用一个 ref 保留之前的 activeKey=== 就是每次更改 activeKey 时就 ref 保存之前的 activeKey ,这样就不用嵌套了,就是写成 if (activeKeyRef.current === "1") {...这样
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2568 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 00:26 · PVG 08:26 · LAX 17:26 · JFK 20:26
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.