useSubmit提交参数异常:下拉框变更时生成错误查询参数求助
问题解决:下拉框自动提交表单时查询参数格式异常
问题描述
下拉选择框内容变更时自动提交表单功能可触发,但生成的查询参数格式异常,例如选择"Green Djinn"后,URL变成:http://localhost:3000/items?0=G&1=r&2=e&3=e&4=n&5=+&6=D&7=j&8=i&9=n&10=n
相关代码
export async function action({ request }) { const body = await request.formData(); } export const loader: LoaderFunction = async ({ request }) => { const url = new URL(request.url); const term = url.searchParams.get('sellers'); console.log('term:', term); const data: LoaderData = { itemList: await db.item.findMany({ where: { seller: term, }, select: { seller: true, price: true, }, }), }; return json(data); }; type LoaderData = { itemList: Array<Item>; }; export default function ItemsRouteIndex() { const submit = useSubmit(); const { itemList } = useLoaderData<LoaderData>(); function handleChange(e) { console.log('e:', e); submit(e, { method: 'get', action: '/items' }); } return ( <Form onChange={(e) => handleChange(e.target.value)}> <select name='sellers'> <option value='Blue Djinn'>Blue Djinn</option> <option value='Green Djinn'>Green Djinn</option> </select> <button type='submit'>Search</button> </Form> ); }
问题原因
handleChange中调用submit时,直接传入了下拉框的字符串值。而useSubmit的第一个参数要求是表单实例、FormData对象或键值对对象,传入纯字符串会被框架当成类数组处理,将每个字符拆分为独立的查询参数,导致格式异常。
修复方案
方案1:直接提交表单实例
修改handleChange函数,通过事件对象获取表单实例并提交:
function handleChange(e) { submit(e.target.form, { method: 'get' }); }
同时调整Form的onChange事件,传递完整的事件对象:
<Form onChange={(e) => handleChange(e)}>
方案2:手动构建FormData提交
如果需要自定义提交数据,可创建FormData并添加指定字段:
function handleChange(selectedValue) { const formData = new FormData(); formData.append('sellers', selectedValue); submit(formData, { method: 'get' }); }
这种写法下,原Form的onChange传value的逻辑可以保留:
<Form onChange={(e) => handleChange(e.target.value)}>
优化点
由于当前组件本身就在/items路由下,submit的action参数可以省略,默认会提交到当前路由,简化代码。
内容的提问来源于stack exchange,提问作者NewbieAeg
相关产品推荐
相关产品推荐

