Home Article Practice useEffect处理表单

useEffect处理表单

2024-07-05 21:29  views:231  source:许某    

通常,我们不仅会用到上面的输入框和按钮,更多的时候是一张表单,
所以也可以在表单中使用useEffect来处理数据请求,逻辑是相同的:
function App() {
...
return (
<Fragment>
<form
onSubmit={() =>
setUrl(`urladdress?query=${query}`)
}
>
<input
type="text"
value={query}
onChange={event =>
setQuery(event.target.value)}
/>
<button type="submit">Search</button>
</form>
{isError && <div>Something went wrong ...</div>}
...
</Fragment>
);
}
上面的例子中,提交表单的时候,会触发页面刷新;就像通常的做法那样,还需要阻止默认事件,来阻止页面的刷新。
function App() {
...
const doFetch = () => {
setUrl(`urladdress?query=${query}`);
};
return (
<Fragment>
<form onSubmit={event => {
doFetch();
event.preventDefault();
}}>
<input
type="text"
value={query}
onChange={event =>
setQuery(event.target.value)}
/>
<button type="submit">Search</button>
</form>
{isError && <div>Something went wrong ...</div>}
...
</Fragment>
);
}



Disclaimer: The above articles are added by users themselves and are only for typing and communication purposes. They do not represent the views of this website, and this website does not assume any legal responsibility. This statement is hereby made! If there is any infringement of your rights, please contact us promptly to delete it.

字符:    改为:
去打字就可以设置个性皮肤啦!(O ^ ~ ^ O)