正文从这开始~

总览

在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig.json文件中把jsx设置为react-jsx,并确保为你的应用程序安装所有必要的@types包。

这里有个例子来展示错误是如何发生的。

// App.ts
import React from 'react'; interface UserCtx {
first: string;
last: string;
age: number;
} const AuthContext = React.createContext<UserCtx | null>(null); const authContext: UserCtx = {
first: 'James',
last: 'Doe',
age: 30,
}; const App = () => {
// ️ Cannot find namespace 'AuthContext'.ts(2503)
return (
<AuthContext.Provider value={authContext}>
<h2>Your app here</h2>
</AuthContext.Provider>
);
}; export default App;

上述代码片段的问题在于,文件的扩展名为.ts ,但是我们在里面编写JSX代码。

tsx

这是不被允许的,因为为了能在TypeScript文件中使用JSX,我们必须这样做:

  1. .tsx扩展名命名文件
  2. tsconfig.json文件中开启jsx选项

确保所有你编写JSX代码的文件都有.tsx扩展名。

// App.tsx
import React from 'react'; interface UserCtx {
first: string;
last: string;
age: number;
} const AuthContext = React.createContext<UserCtx | null>(null); const authContext: UserCtx = {
first: 'James',
last: 'Doe',
age: 30,
}; const App = () => {
return (
<AuthContext.Provider value={authContext}>
<h2>Your app here</h2>
</AuthContext.Provider>
);
}; export default App;

更新完文件的扩展名为.tsx后,如果问题仍未解决,请尝试重启你的IDE和开发服务器。

打开tsconfig.json文件,并确保jsx选项被设置为react-jsx

// tsconfig.json
{
"compilerOptions": {
"jsx": "react-jsx", // ️ make sure you have this
"target": "es6",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true
},
"include": ["src/**/*"]
}

jsx选项被设置为react-jsx时,它会导致编译器抛出.js文件,其中的JSX被改为_jsx调用。

如有必要请重启你的IDE和开发服务器。你的开发服务器不会接收这些变化,直到你停止它并重新运行npm start命令。

安装@types/包

在React中出现"Cannot find namespace context"错误的另一个原因是,我们没有安装必要的@types/包。

在项目的根路径下打开终端,并运行以下命令:

# ️ with NPM
npm install --save-dev @types/react @types/react-dom @types/node @types/jest typescript # ------------------------------------------------------ # ️ with YARN
yarn add @types/react @types/react-dom @types/node @types/jest typescript --dev

该命令为reactreact-domnodejest安装类型声明文件,并安装typescript包。

如果仍然报错,尝试删除node_modulespackage-lock.json文件(不是package.json),重新运行npm install并重启你的IDE。

# ️ delete node_modules and package-lock.json
rm -rf node_modules
rm -f package-lock.json
rm -f yarn.lock # ️ clean npm cache
npm cache clean --force npm install

如果错误仍然存在,请确保重新启动你的IDE和开发服务器。VSCode经常出现故障,重启有时会解决一些问题。

手动添加

如果你仍然得到"Cannot find namespace Context"的错误,打开你的package.json文件,确保它在devDependencies对象中包含以下包。

// package.json
{
// ... rest
"devDependencies": {
"@types/jest": "^27.4.1",
"@types/node": "^17.0.24",
"@types/react": "^18.0.5",
"@types/react-dom": "^18.0.1",
"typescript": "^4.6.3"
}
}

你可以尝试手动添加上述依赖,并重新运行npm install

npm install

或者安装依赖包的最新版本:

# ️ with NPM
npm install --save-dev @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest # ------------------------------------------------------ # ️ with YARN
yarn add @types/react@latest @types/react-dom@latest @types/node@latest @types/jest@latest typescript@latest --dev

React报错之Cannot find namespace context的更多相关文章

  1. MVC模式下unity配置,报错“No connection string named '**Context' could be found in the application config file”

     写在前面: 第一次配置时好好的,后来第二次改到MVC模式,把依赖注入写成字典的单例模式时,由于新建的ORM(数据库映射模型EF),怎么弄都不用,一直报错"No connection str ...

  2. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  3. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

  4. react报错 TypeError: Cannot read property 'setState' of undefined

    代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...

  5. Django报错:'Specifying a namespace in include() without providing an app_name '

    环境:win10(64)+pycharm2018.3+python3.7 在网页项目中使用include()方法 项目目录中同时存在app/urls.py和proj/urls.py 在proj/url ...

  6. React报错之Cannot find name

    正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...

  7. React报错之Expected `onClick` listener to be a function

    正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...

  8. React报错:Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix,

    今天在开发时报了以下错误,记录一下 我们不能在组件销毁后设置state,防止出现内存泄漏的情况 出现原因直接告诉你了,组件都被销毁了,还设置个锤子的state啊 解决方案: 利用生命周期钩子函数:co ...

  9. react报错this.setState is not a function

    当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ...

随机推荐

  1. 联发科 (MTK) sensor bring up

    MT6768平台 1.添加驱动文件 2.添加硬件配置支持 3.添加硬件配置 4.添加编译配置 5.分配空间(非必要,当代码量超过当前空间大小时将会报错,根据报错log改大小即可.) 6.兼容配置 7. ...

  2. python基础学习5

    Python的基础学习5 内容概要 流程控制理论 if判断 while循环 内容详情 流程控制理论 # 流程控制:即控制事物执行的流程 # 执行流程的分类 1.顺序结构 从上往下按顺序依次执行 2.分 ...

  3. CabloyJS全栈开发之旅(1):NodeJS后端编译打包全攻略

    背景 毋庸置疑,NodeJS全栈开发包括NodeJS在前端的应用,也包括NodeJS在后端的应用.CabloyJS前端采用Vue+Framework7,采用Webpack进行打包.CabloyJS后端 ...

  4. python实现对简单的运算型验证码的识别【不使用OpenCV】

    最近在写我们学校的教务系统的手机版,在前端用户执行绑定操作后,服务器将执行登录,但在登录过程中,教务系统中有个运算型的验证码,大致是这个样子的: 下面我们开始实现这个验证码的识别. 1.图片读取 从网 ...

  5. BUUCTF-小明的保险箱

    小明的保险箱 16进制打开可以发现存在一个RAR压缩包,压缩包里面应该就是flag文本 使用ARCHPR破解即可

  6. 二:动手实操SpringBoot-使用Spring Initializr创建项目

    使用 Spring Initializr 初始化 Spring Boot 项目 Spring Initializr 从本质上说就是一个Web应用程序,它能为你构建Spring Boot项目结构. 虽然 ...

  7. 使用Java编写一个日期时间封装类

    package base; import java.util.GregorianCalendar; import java.util.StringTokenizer; import java.util ...

  8. 《The Tail At Scale》论文详解

    简介 用户体验与软件的流畅程度是呈正相关的,所以对于软件服务提供方来说,保持服务耗时在用户能接受的范围内就是一件必要的事情.但是在大型分布式系统上保持一个稳定的耗时又是一个很大的挑战,这篇文章解析的是 ...

  9. 基于.NetCore开发博客项目 StarBlog - (13) 加入友情链接功能

    系列文章 基于.NetCore开发博客项目 StarBlog - (1) 为什么需要自己写一个博客? 基于.NetCore开发博客项目 StarBlog - (2) 环境准备和创建项目 基于.NetC ...

  10. nextInt和nextLine以及next方法的区别

    1.nextInt() 只读取整型的数据,输入读取完之后,光标仍在当前行. 2.nextLine() 扫描到一行内容,当遇见换行符时,结束扫描.一旦输入读取完毕,该方法会将光标移到下一行开始的位置. ...