You need to enable JavaScript to run this app. React中条件调用useContext触发react-hooks-nesting TSLint报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

React中条件调用useContext触发react-hooks-nesting TSLint报错如何解决

问题解决方案

错误原因

你遇到的报错是因为违反了React Hook的核心调用规则:所有Hook必须在组件/自定义Hook的最顶层无条件调用,不能出现在条件判断、短路运算、循环或返回语句之后。
你原代码中的const resources = inputResources || useResourceScope();属于短路条件调用:当inputResources为真值时,useResourceScope(内部调用了useContext)不会被执行,不同渲染场景下Hook调用次数不一致,因此触发校验报错。
你自行修改的方案运行失败的核心原因是:你将createContext放在了useResourceScope内部,每次Hook执行都会生成全新的Context实例,useContext接收不同的Context实例会导致不可预期的重渲染和取值失败。

正确实现方案

核心逻辑:先无条件调用useContext,再判断是否要使用传入的inputResources。Hook规则只要求调用顺序和数量稳定,不要求必须使用Hook的返回值,该方案完全不影响原有功能,开销可忽略。

修改后的useResourceScope代码(Component2)

import { createContext } from 'preact';
import { useContext } from 'preact/hooks';

export const ResourceScopeContext = createContext<ResourceScope | undefined>(undefined);

export function useResourceScope(inputResources?: ResourceScope): ResourceScope {
  // 无条件顶层调用useContext,符合Hook规则
  const contextResources = useContext(ResourceScopeContext);

  // 传入了自定义资源则直接返回,忽略Context取值
  if (inputResources) {
    return inputResources;
  }

  // 未传资源则走原有Context校验逻辑
  if (!contextResources) {
    throw new Error('error message');
  }
  return contextResources;
}

Component1代码无需额外调整,保持你修改后的调用逻辑即可

import { useEffect } from 'react';

export function useSubscribeListItemStore(
  inputResources?: ResourceScope
) {
  const resources = useResourceScope(inputResources);
  const listItemStore = resources.consume(listItemStoreKey);
  
  useEffect(function subscribeListItemStore() {
    // do some logic
  }, []);
}

方案验证

  • 功能完全对齐原有逻辑:传inputResources时优先用传入值,未传时取Context值,缺失时抛出对应错误
  • 完全符合Hook调用规则,不会触发TSLint/ESLint校验报错
  • 无额外性能开销,useContext本身的执行成本可以忽略不计

内容的提问来源于stack exchange,提问作者LearnToImprove

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 16:15:04