为什么我得到 - 比之前的渲染呈现更多的钩子

Why I'm getting - Rendered more hooks than during the previous render

我有一个名为 useComments 的挂钩。

当我硬编码时,

const { comments1 } = useComments(requests[l].id, true);
const { comments2 } = useComments(requests[l].id, true);
const { comments3 } = useComments(requests[l].id, true);

我得到了想要的输出。

但是当我使用 for 循环 获取存储在数组中的 ID 时,我得到 'Rendered more hooks than during the previous render.' 错误。

for (let l = 0; l < 2; l++) {
  const { comments } = useComments(requests[l].id, true);
  console.log({ [l]: comments });
}

这是对 React hooks 的限制,因为 在 return 之前的单个组件中的 hooks 数量必须是常量。

您可以做什么 - 只需将其分解成一个组件,该组件具有固定数量的挂钩 - 只有一个:

function Comments({ requestId }) {
  const { comments } = useComments(requestId, true);
  console.log({ [l]: comments });
  
  return null
}

function Wrapper() {
  const requestIds = []
  for (let l = 0; l < 2; l++) {
    requestIds.push(requests[l].id)
  }
  // note we don't use any hooks here.
  
  return requestIds.map((requestId) => <Comments requestId={requestId} />
}