简体   繁体   中英

How to prevent a state update on a react onClick function (outside useEffect)?

When I use useEffect I can prevent the state update of an unmounted component by nullifying a variable like this

useEffect(() => {
 const alive = {state: true}
//...
if (!alive.state) return
//...
 return () => (alive.state = false)
}

But how to do this when I'm on a function called in a button click (and outside useEffect )?

For example, this code doesn't work

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
  }
}

or this 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') 
  }
}

When a component re-renders, it will garbage collect the variables of the current context, unless they are state-full. If you want to persist a value across renders, but don't want to trigger a re-renders when you update it, use the useRef hook. 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') 
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM