为何我的fetch请求方法变为GET而非POST?添加age字段后异常
问题分析与解决方案
核心原因
你的问题本质和添加age相关代码无关,是表单默认提交行为未被阻止导致的:
- 点击
<input type="submit">时,浏览器会自动触发表单的默认提交逻辑——如果表单没指定method属性,就会以GET方式刷新页面。这个默认行为会覆盖你手动调用的fetch POST请求,导致你在网络面板看到GET请求。 - 之前代码“正常”是偶然因素(比如请求在页面刷新前完成,但默认行为一直存在),添加
age后渲染或状态更新的时机变化,让默认行为的GET请求被优先捕获到。
修复步骤
1. 阻止表单默认提交行为
修改handleClick函数,添加e.preventDefault()阻止默认行为:
function handleClick(e){ e.preventDefault(); // 关键:阻止表单默认提交逻辑 const newFriend = { name: name, birthday: birthday, age: age, } console.log(newFriend) props.addNewFriend(newFriend) }
2. 规范写法优化(可选)
直接监听表单的onSubmit事件,比监听按钮onClick更符合表单交互逻辑:
return ( <div> <form id='friendform' onSubmit={handleClick}> <input type='text' placeholder='name' name='name' id='name' onChange={(e) => setName(e.target.value)} /> <input type='date' placeholder='birthday' name='birthday' id='birthday' onChange={(e) => setBirthday(e.target.value)} /> <input type='text' placeholder='age' name='age' id='age' onChange={(e) => setAge(e.target.value)} /> <input type='submit' value='submit' /> </form> </div> )
3. 修正状态更新错误
addNewFriend里的状态更新存在逻辑错误,当前写法会重复添加API返回的数据,改成基于之前状态的更新方式:
const addNewFriend = async (friend) => { try { const resp = await fetch(FRIEND_END, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(friend), }); if (resp.ok) { const newFriend = await resp.json(); setData(prevData => [...prevData, newFriend]); // 基于旧状态更新,避免闭包问题 } } catch (e) { console.log('addNewFriend had an error:', e); } };
验证方式
修改后提交表单,检查网络面板:
- 只会出现一个
POST请求,无GET请求 - 页面不会自动刷新,本地状态正常更新
内容的提问来源于stack exchange,提问作者ProfessorSocks
相关产品推荐
相关产品推荐

