[英]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
时,我可以通过使这样的变量无效来防止未安装组件的 state 更新
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
)?但是,当我在按钮单击中调用的 function 上(以及在
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.如果您想在渲染中保留一个值,但不想在更新时触发重新渲染,请使用
useRef
挂钩。 https://reactjs.org/docs/hooks-reference.html#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')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.