1.3 KiB
1.3 KiB
title, impact, impactDescription, tags
| title | impact | impactDescription | tags |
|---|---|---|---|
| 将交互逻辑放在事件处理器中 | MEDIUM | 避免 Effect 重复执行和重复的副作用 | rerender, useEffect, 事件, 副作用, 依赖 |
将交互逻辑放在事件处理器中
如果某个副作用是由特定的用户操作(提交、点击、拖拽)触发的,请在该事件处理器中直接执行它。不要将操作建模为「状态 + Effect」的形式;这会导致 Effect 在无关变更时重新执行,并可能重复触发该操作。
错误做法(将事件建模为状态 + Effect):
function Form() {
const [submitted, setSubmitted] = useState(false)
const theme = useContext(ThemeContext)
useEffect(() => {
if (submitted) {
post('/api/register')
showToast('Registered', theme)
}
}, [submitted, theme])
return <button onClick={() => setSubmitted(true)}>Submit</button>
}
正确做法(在处理器中执行):
function Form() {
const theme = useContext(ThemeContext)
function handleSubmit() {
post('/api/register')
showToast('Registered', theme)
}
return <button onClick={handleSubmit}>Submit</button>
}
参考链接:这段代码是否应该移到事件处理器中?