如何强制调用 React.js 钩子的顺序

How to force a order for calling React.js hooks

是否可以强制使用 React hooks 的特定顺序?例如,某些 linting/prettier 设置将始终确保首先使用 'useState' 挂钩,然后才使用 'useEffect' 挂钩。假设我有以下代码:

const MyComponent = () => {
    const [myState1, setMyState1] = React.useState();
    const [myState2, setMyState2] = React.useState();

    React.useEffect(() => {
        runSomeEffect()
    }, [])

    const [myState3, setMyState3] = React.useState();

    return <div>...</div>
}

我想发出某种警告,即第三个 useState 挂钩应移至顶部。我查看了 Eslint 和 Prettier,但我认为其中任何一个都没有强制执行 React 钩子顺序的规则。

由于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

因此,这样的规则可能会导致意外行为,即开发人员强制执行命令而规则会破坏它。