React:在循环和嵌套函数内部调用Hook的错误示例

时间:2019-10-26 09:15:05

标签: reactjs react-hooks

挂钩的第一条规则是仅在顶层调用挂钩,即“不要在循环,条件或嵌套函数内调用挂钩”。文档explains pretty clearly with an example for calling Hooks inside conditions,但不适用于其他两种情况:循环和嵌套函数。

是否有示例在循环和嵌套函数中调用Hook时会出错?而且,自定义钩子不只是嵌套函数吗?

不幸的是,herehere这两个相关问题的答案仅给出了正确的例子。

1 个答案:

答案 0 :(得分:2)

可变长度循环的示例:

const {useState} = React

const WrongLoop = () => {
  const [count, setCount] = useState(1)
  for (let i = 0; i < count; i++) {
    const [x, setX] = useState(i)
  }
  const [unknownOrder, setUnknownOrder] = useState('some state')
  
  return <button onClick={() => setCount(c => c+ 1)}>{count} {unknownOrder}</button>
}

ReactDOM.render(<WrongLoop />, document.getElementById('root'))
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

eslint很难检测到的嵌套函数示例(自定义钩子是一种特殊情况-在函数名称中使用use...前缀时,eslint可以静态分析其在组件中的用法):< / p>

const {useState} = React

const fn = () => {
  const [x, setX] = useState() // is it OK to use hooks unconditionally here?
}

const WrongFn = () => {
  const [count, setCount] = useState(1)
  if (count === 1) {
    fn() // OK to use normal functions conditionally.. but what if there's a hook inside?
  }
  const [unknownOrder, setUnknownOrder] = useState('some state')
  
  return <button onClick={() => setCount(c => c+ 1)}>{count} {unknownOrder}</button>
}

ReactDOM.render(<WrongFn />, document.getElementById('root'))
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>