【问题标题】:Cannot find namespace 'GameContext' [duplicate]找不到命名空间“GameContext”[重复]
【发布时间】:2021-05-22 21:36:01
【问题描述】:

我正在尝试在 React with Typescript 中使用 useContext 钩子。我收到一条错误消息,提示 Cannot find namespace 'GameContext'.

我在常规 .js 中使用了相同的语法,但在 Typescript 中它似乎不起作用。

import { createContext, useState } from 'react';

export const GameContext = createContext();

export const GameProvider = (props) => {
  const [game, setGame] = useState({});

  return (
    <GameContext.Provider value={[game, setGame]}>
      {props.children}
    </GameContext.Provider>
  )
}

【问题讨论】:

  • 能否贴出详细的错误信息

标签: reactjs typescript


【解决方案1】:

该特定错误消息很奇怪(堆栈跟踪会有所帮助),但我可以立即看到您没有正确键入上下文或提供初始值。初始值在 JS 中是可选的,但在 TS 中是必需的。

import React, { createContext, useState, useContext, Dispatch, SetStateAction, PropsWithChildren } from 'react';

// replace this with your actual type
type Game = {}

// tuple with the same types as the useState tuple
type GameContextValue = [ Game, Dispatch<SetStateAction<Game>> ]

// set an initial value with a game and setGame that fulfill the expected type
export const GameContext = createContext<GameContextValue>([
    {}, 
    () => console.error("attempted to use GameContext outside of a Provider")
]);

// need to set a type for props which includes children
export const GameProvider = (props: PropsWithChildren<{}>) => {
  // need to declare the type for the state
  const [game, setGame] = useState<Game>({});

  return (
    <GameContext.Provider value={[game, setGame]}>
      {props.children}
    </GameContext.Provider>
  )
}

const Test = () => {
    // game and setGame get proper types
    const [game, setGame] = useContext(GameContext);
}

Playground Link

【讨论】:

    猜你喜欢
    • 2013-07-14
    • 2011-06-13
    • 2018-02-09
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    • 2015-06-20
    • 2012-07-14
    相关资源
    最近更新 更多