You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Context搭配Typescript使用时IBlockchainContext类型校验报错问题

问题根因

代码存在两处核心类型不匹配错误,就是你看到的lint报错来源:

  • Context泛型定义错误:你要通过Context传递的是包含state和dispatch的IBlockchainContextValue类型对象,但调用createContext时错误传入了IBlockchainContextState作为泛型参数,和后续Provider传递的实际值类型完全不匹配。
  • Provider组件props类型错误:React.FC的泛型参数是组件接收的外部props类型,你的Provider组件仅接收children属性,错误传入IBlockchainContextValue作为泛型参数导致类型校验失败。
  • 冗余代码:你已经使用useReducer管理全局状态,代码中声明的loading、account等多个独立useState从未被使用,可以直接删除。
修复后完整代码
// Blockchain context
import React from 'react';

interface IBlockchainContextState {
  loading: boolean;
  account: string;
  tokemonToken: any; // TODO
  web3: any; // TODO
  errorMessage: string;
}

interface IBlockchainContextValue {
  state: IBlockchainContextState;
  dispatch: React.Dispatch<any>;
}

const initialState: IBlockchainContextState = {
  loading: false,
  account: '',
  tokemonToken: null,
  web3: null,
  errorMessage: '',
};

// 修正:Context泛型改为IBlockchainContextValue,传入对应结构的初始值
const initialContextValue: IBlockchainContextValue = {
  state: initialState,
  dispatch: () => {} // 初始占位dispatch,Provider挂载后会被实际值覆盖
}
const BlockchainContext = React.createContext<IBlockchainContextValue>(initialContextValue);

// 修正:Provider组件泛型改为实际接收的props类型,仅包含children
const BlockchainContextProvider: React.FC<{ children: React.ReactNode }> = ({
  children,
}) => {
  const blockchainReducer = (
    state: IBlockchainContextState,
    action: any
  ): IBlockchainContextState => {
    switch (action.type) {
      case 'SET_LOADING':
        return { ...state, loading: action.payload };
      case 'SET_ACCOUNT':
        return { ...state, account: action.payload };
      case 'SET_TOKEN':
        return { ...state, tokemonToken: action.payload };
      case 'SET_WEB3':
        return { ...state, web3: action.payload };
      case 'SET_ERROR_MESSAGE':
        return { ...state, errorMessage: action.payload };
      default:
        return state;
    }
  };

  const [state, dispatch] = React.useReducer(blockchainReducer, initialState);

  const blockchainContextValue = React.useMemo(
    () => ({
      state,
      dispatch,
    }),
    [state, dispatch]
  );

  return (
    <BlockchainContext.Provider value={blockchainContextValue}>
      {children}
    </BlockchainContext.Provider>
  );
};

export { BlockchainContext, BlockchainContextProvider };

内容的提问来源于stack exchange,提问作者a-s-r-789

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 03:27:03