React报错之Cannot find namespace context
正文从这开始~
总览
在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,我们必须这样做:
- 以
.tsx扩展名命名文件 - 在
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
该命令为react,react-dom,node,jest安装类型声明文件,并安装typescript包。
如果仍然报错,尝试删除node_modules和package-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的更多相关文章
- MVC模式下unity配置,报错“No connection string named '**Context' could be found in the application config file”
写在前面: 第一次配置时好好的,后来第二次改到MVC模式,把依赖注入写成字典的单例模式时,由于新建的ORM(数据库映射模型EF),怎么弄都不用,一直报错"No connection str ...
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- React报错 :browserHistory doesn't exist in react-router
由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...
- react报错 TypeError: Cannot read property 'setState' of undefined
代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...
- 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 ...
- React报错之Cannot find name
正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...
- React报错之Expected `onClick` listener to be a function
正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...
- 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 ...
- react报错this.setState is not a function
当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ...
随机推荐
- 动态调试JS脚本文件:(JS源映射 - sourceURL)与 debugger
我们在进行js调试时经常会对js进行调试,chrome 对js提示对支持非常友好,只需要F12就可以打开chrome的调试器 在sources里面就是页面请求后加载的一些资源文件,我们可以找到我们的j ...
- Tensorboard SummaryWriter()
import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvi ...
- GDKOI 2021 Day1 TG 。。。
看着一群群比 LHF , HQX 还强的大佬涌进了机房,本蒟蒻表示慌得一批 T1 讲题人说最简单的签到题本蒟蒻表示... \(Update\) 用 ds , dt 两个变量记录点 i 连向 s 或 t ...
- 如何优化PlantUML流程图(时序图)
这篇文章用来介绍,如何画出好看的流程图. 1. 选择合适的组件 1.1 plantuml官方提供的组件 1.2 加载图片 1.2.1 加载本地图片 1.2.2 加载网络图片 1.2.3 图片资源 2. ...
- ”只用 1 分钟“ - 超简极速 Apk 签名 & 多渠道打包神器
众所周知,渠道包作为当下国内 Android 应用市场常见的分发方式,当 APP 和后台交互或进行数据上报时,会带上各自的 channel 渠道信息,以此方便企业 & 开发者统计 APP 在各 ...
- Elasticsearch学习系列二(基础操作)
本文将分为3块讲解Es的基础操作.分别为:索引(index).映射(mapping).文档(document). 索引操作 创建索引库 语法: PUT /索引名称{ "settings&qu ...
- TypeScript(4)接口
介绍 TypeScript 的核心原则之一是对值所具有的结构进行类型检查.我们使用接口(Interfaces)来定义对象的类型.接口是对象的状态(属性)和行为(方法)的抽象(描述) 接口初探 声明接口 ...
- NC14683 储物点的距离
NC14683 储物点的距离 题目 题目描述 一个数轴,每一个储物点会有一些东西,同时它们之间存在距离. 每次给个区间 \([l,r]\) ,查询把这个区间内所有储物点的东西运到另外一个储物点的代价是 ...
- MyBatis项目创建
一.开发环境的准备 总览: mybatis搭建过程: 1.导入jar 2.创建mybatis的核心(全局)配置文件mybatis-config.xml,并配置 3.创建映射文件XxxMapper.xm ...
- java-Stream的总结
JAVA中的Stream 01.什么是Stream Stream是JDK8中引入,Stream是一个来自数据源的元素序列并支持聚合操作.可以让你以一种声明的方式处理数据,Stream 使用一种类似用 ...