是否可以强制执行 React hooks 的特定使用顺序?例如,一些 linting/prettier 设置将始终确保首先使用“useState” Hook ,然后才使用“useEffect” Hook 。假设我有以下代码:
const MyComponent = () => {
const [myState1, setMyState1] = React.useState();
const [myState2, setMyState2] = React.useState();
React.useEffect(() => {
runSomeEffect()
}, [])
const [myState3, setMyState3] = React.useState();
return <div>...</div>
}
我想收到某种警告,即第三个 useState
Hook 应移至顶部。我研究了 Eslint 和 Prettier,但我认为它们都没有强制执行 React hooks 顺序的规则。
最佳答案
你不能有这样的规则,因为钩子(Hook)的调用顺序很重要,因为 Rules of Hooks .
By following this rule, you ensure that Hooks are called in the same order each time a component renders. That’s what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.
您对原因有深入的解释,here .
React relies on the order in which Hooks are called
因此,这样的规则可能会导致意外行为,开发人员会强制执行命令,而规则会破坏它。
关于javascript - 如何强制调用 React.js Hook 的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65775856/