在 if 语句中调用 useState hook 的 setter 是否意味着 BREAKING RULES OF HOOKS? [英] Does calling setter of useState hook inside if statement imply BREAKING RULES OF HOOKS?

查看:81
本文介绍了在 if 语句中调用 useState hook 的 setter 是否意味着 BREAKING RULES OF HOOKS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React 文档声明:不要在循环、条件或嵌套函数内调用 Hook.

React docs state: don’t call Hooks inside loops, conditions, or nested functions.

是否调用钩子意味着只是调用useState,例如const [state, useState] = useState(0)?

Does calling a hook means just calling useState e.g. const [state, useState] = useState(0)?

在条件语句中调用 setter 怎么样?

What about calling setter in conditionals ?

这是否违反了钩子的规则?

Is this code breaking rules of hooks ?

const [oneHook, setOneHook] = useState(0)
const [anotherHook, setAnotherHook] = useState(false)

if (something) {
   setOneHook(1)
   setAnotherHook(true)
} else {
     setOneHook(0);
     setAnotherHook(false)
}

谢谢!

推荐答案

不,该代码示例没有违反钩子的规则.每次组件渲染时,都会以完全相同的顺序对 useState 进行相同数量的调用,这样就可以了.

No, that code example does not break the rules of hooks. Every time the component renders there will be exactly the same number of calls to useState in exactly the same order, so that will be fine.

我确实想指出立即在组件主体中设置状态没有多大意义.当组件挂载时,它将使用 state 中的初始值开始渲染,但在它完成渲染之前,状态已经改变,它必须重新开始.但据推测,这只是示例的一个工件,在您的实际代码中,if 将位于 useEffect 或其他一些实际代码位置内.

I do want to point out that setting state right away in the body of the component doesn't make much sense. When the component mounts it will start rendering with the initial values from state, but then before it can finish rendering the state has already changed and it has to start over. But presumably that's just an artifact of the example, and in your real code the if would be inside a useEffect or some other practical code location.

这篇关于在 if 语句中调用 useState hook 的 setter 是否意味着 BREAKING RULES OF HOOKS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆