如何防止对反应 onClick 函数(在 useEffect 之外)进行状态更新?
How to prevent a state update on a react onClick function (outside useEffect)?
当我使用 useEffect
时,我可以通过取消这样的变量来阻止未安装组件的状态更新
useEffect(() => {
const alive = {state: true}
//...
if (!alive.state) return
//...
return () => (alive.state = false)
}
但是当我在单击按钮(以及 useEffect
之外)调用的函数时如何执行此操作?
例如,此代码不起作用
export const MyComp = () => {
const alive = { state: true}
useEffect(() => {
return () => (alive.state = false)
}
const onClickThat = async () => {
const response = await letsbehere5seconds()
if (!alive.state) return
setSomeState('hey')
// warning, because alive.state is true here,
// ... not the same variable that the useEffect one
}
}
或者这个
export const MyComp = () => {
const alive = {}
useEffect(() => {
alive.state = true
return () => (alive.state = false)
}
const onClickThat = async () => {
const response = await letsbehere5seconds()
if (!alive.state) return // alive.state is undefined so it returns
setSomeState('hey')
}
}
当组件重新渲染时,它将垃圾收集当前上下文的变量,除非它们是全状态的。如果你想在渲染中保留一个值,但不想在更新它时触发重新渲染,请使用 useRef
挂钩。
https://reactjs.org/docs/hooks-reference.html#useref
export const MyComp = () => {
const alive = useRef(false)
useEffect(() => {
alive.current = true
return () => (alive.current = false)
}
const onClickThat = async () => {
const response = await letsbehere5seconds()
if (!alive.current) return
setSomeState('hey')
}
}
当我使用 useEffect
时,我可以通过取消这样的变量来阻止未安装组件的状态更新
useEffect(() => {
const alive = {state: true}
//...
if (!alive.state) return
//...
return () => (alive.state = false)
}
但是当我在单击按钮(以及 useEffect
之外)调用的函数时如何执行此操作?
例如,此代码不起作用
export const MyComp = () => {
const alive = { state: true}
useEffect(() => {
return () => (alive.state = false)
}
const onClickThat = async () => {
const response = await letsbehere5seconds()
if (!alive.state) return
setSomeState('hey')
// warning, because alive.state is true here,
// ... not the same variable that the useEffect one
}
}
或者这个
export const MyComp = () => {
const alive = {}
useEffect(() => {
alive.state = true
return () => (alive.state = false)
}
const onClickThat = async () => {
const response = await letsbehere5seconds()
if (!alive.state) return // alive.state is undefined so it returns
setSomeState('hey')
}
}
当组件重新渲染时,它将垃圾收集当前上下文的变量,除非它们是全状态的。如果你想在渲染中保留一个值,但不想在更新它时触发重新渲染,请使用 useRef
挂钩。
https://reactjs.org/docs/hooks-reference.html#useref
export const MyComp = () => {
const alive = useRef(false)
useEffect(() => {
alive.current = true
return () => (alive.current = false)
}
const onClickThat = async () => {
const response = await letsbehere5seconds()
if (!alive.current) return
setSomeState('hey')
}
}