Router 6中如何在handler内获取useFetcher Form的method属性?
在Remix的useFetcher handler中获取表单的method值
你遇到的问题是因为Remix的fetcher.formMethod并不会自动关联你在fetcher.Form上定义的method属性——这个属性只有当表单通过默认提交行为触发请求时,才会被赋值到fetcher实例上。手动调用fetcher.submit时,需要显式指定method参数。
给你几个可行的解决办法:
方法一:直接显式指定method
既然你已经在form里写死了method='POST',直接在handler里传入method: 'POST'即可,简单直接:
const fetcher = useFetcher() const handlerLogin = useCallback(async () => { fetcher.submit({ value: 'social' }, { method: 'POST', action: '/' }) }, [fetcher]) return ( <Card className={styles.loginCard}> <fetcher.Form method='POST' action='/'> {/* 表单内容 */} </fetcher.Form> </Card> )
方法二:用Ref获取表单的method属性
如果form的method是动态变化的,或者不想重复写死,可以给表单加个ref,直接从DOM元素上读取method:
const fetcher = useFetcher() const formRef = useRef(null) const handlerLogin = useCallback(async () => { // 读取form的method,默认 fallback 到POST const formMethod = formRef.current?.method || 'POST' fetcher.submit({ value: 'social' }, { method: formMethod, action: '/' }) }, [fetcher]) return ( <Card className={styles.loginCard}> <fetcher.Form ref={formRef} method='POST' action='/'> {/* 表单内容 */} </fetcher.Form> </Card> )
方法三:统一管理method状态
如果需要动态修改method,可以把它存在状态里,让表单和handler共用同一个值:
const fetcher = useFetcher() // 静态值直接定义,动态场景用useState const formMethod = 'POST' const handlerLogin = useCallback(async () => { fetcher.submit({ value: 'social' }, { method: formMethod, action: '/' }) }, [fetcher, formMethod]) return ( <Card className={styles.loginCard}> <fetcher.Form method={formMethod} action='/'> {/* 表单内容 */} </fetcher.Form> </Card> )
总结一下:fetcher.formMethod是为表单默认提交场景设计的,手动调用submit时必须自己传入method参数,通过上面几种方式就能保证和表单定义的method一致。
内容的提问来源于stack exchange,提问作者D. Rattansingh
相关产品推荐
相关产品推荐

