代码之家  ›  专栏  ›  技术社区  ›  D. Rattansingh

在Router 6 useFetcher Form中检索方法

  •  1
  • D. Rattansingh  · 技术社区  · 2 年前

    我别无选择,只能在处理程序中调用fetcher的submit方法。它正在访问路由器中的正确操作方法,但我无法将该方法传递给操作,即。 method='POST 在窗体中定义。如何访问的方法 fetch.Form 在处理程序内部?

    const fetcher = useFetcher()
    
    const handlerLogin = useCallback(async () => {
      console.log(fetcher.formMethod) //-> outputting undefined
      fetcher.submit({ value: 'social' }, { method: fetcher.formMethod })
    },[])
        
    return (
      <Card className={styles.loginCard}>
        <fetcher.Form method='POST' action='/'>
          ..............
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   dom1    2 年前

    尝试此解决方案,将方法传递给 handlerLogin 功能:

    const fetcher = useFetcher();
    
    const handlerLogin = useCallback(async (formMethod) => {
      fetcher.submit({ value: 'social' }, { method: formMethod });
    }, []);
    
    return (
      <Card className={styles.loginCard}>
        <fetcher.Form
          method='POST'
          action='/'
        >
          {/* other parts ... */}
          <button onClick={() => handlerLogin(fetcher.formMethod)}>
            Submit
          </button>
        </fetcher.Form>
      </Card>
    );
    
        2
  •  1
  •   Drew Reese    2 年前

    handlerLogin 正在被备忘录化,并且正在关闭 fetcher 初始渲染周期的值。 提取器 是一个外部依赖项,因此应将其包含在 useCallback hook的依赖数组。

    const fetcher = useFetcher();
    
    const handlerLogin = useCallback(() => {
      console.log(fetcher.formMethod);
      fetcher.submit({ value: 'social' }, { method: fetcher.formMethod });
    }, [fetcher]);
    

    因为这可能只会传递给RRD Form 我怀疑 使用回调 挂钩甚至是必要的,可能会被移除。

    const fetcher = useFetcher();
    
    const handlerLogin = () => {
      console.log(fetcher.formMethod);
      fetcher.submit({ value: 'social' }, { method: fetcher.formMethod });
    };
    
    推荐文章