React报错之Cannot assign to 'current' because it is a read-only property
正文从这开始~
总览
当我们用一个null值初始化一个ref,但在其类型中不包括null时,就会发生"Cannot assign to 'current' because it is a read-only property"错误。为了解决该错误,请在ref的类型中包含null。比如说,const ref = useRef<string | null>(null) 。
这里有个例子来展示错误是如何发生的。
// App.tsx
import {useEffect, useRef} from 'react';
const App = () => {
const ref = useRef<string>(null);
useEffect(() => {
// ️ Error: Cannot assign to 'current' because it is a read-only property.ts(2540)
ref.current = 'hello';
}, []);
return (
<div>
<h2>hello world</h2>
</div>
);
};
export default App;
上面例子的问题在于,当我们将null作为初始值传递到useRef钩子中时,并且我们传递给钩子的泛型中没有包括null类型,我们创建了一个不可变的ref对象。
正确的泛型
为了解决该错误,我们必须在传递给钩子的泛型中包括null类型。
// App.tsx
import {useEffect, useRef} from 'react';
const App = () => {
// ️ include null in the ref's type
const ref = useRef<string | null>(null);
useEffect(() => {
ref.current = 'hello';
}, []);
return (
<div>
<h2>hello world</h2>
</div>
);
};
export default App;
在ref的类型中,我们使用联合类型来包括null类型,这使它成为可变ref对象。
现在这个例子中
ref的类型是字符串或null,它的current属性可以赋值为这两种类型中的任意一种的值。
DOM元素
如果你的引用指向一个DOM元素,情况也是一样的。如果你需要改变ref的current属性的值,你必须将钩子的类型定为 const ref = useRef<HTMLElement | null>(null)。
注意,如果你不直接赋值给它的current属性,你不必在 ref 的类型中包含 null。
// App.tsx
import {useEffect, useRef} from 'react';
const App = () => {
const ref = useRef<HTMLInputElement>(null);
useEffect(() => {
ref.current?.focus();
}, []);
return (
<div>
<input ref={ref} type="text" defaultValue="" />
</div>
);
};
export default App;
上述例子中的ref是用来聚焦input元素的。因为没有对其.current属性进行赋值,所以没有必要在其类型中包含null。
React报错之Cannot assign to 'current' because it is a read-only property的更多相关文章
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- vue运行报错error:Cannot assign to read only property 'exports' of object '#<Object>'
用weex做项目的时候,npm start 之后一直报错error:Cannot assign to read only property 'exports' of object '#<Obje ...
- Spring+Hibernate4 Junit 报错No Session found for current thread
论坛上有另外一篇更全面的帖子,jinnianshilongnian写的:http://www.iteye.com/topic/1120924 本文的环境是: spring-framework-3.1 ...
- 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 ...
- React报错之Cannot find name
正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...
- React报错之Cannot find namespace context
正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...
- 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 ...
随机推荐
- python字符编码与文件操作
目录 字符编码 字符编码是什么 字符编码的发展史 字符编码实际应用 编码与解码 乱码问题 python解释器层面 文件操作 文件操作简介 文件的内置方法 文件的读写模式 文件的操作模式 作业 答案 第 ...
- 【FineBI】FineBI连接阿里云mysql教程
因为某些原因需要查看数据信息,之前连接成功一次,今天软件更新了以后发现连接信息丢. 又重新折腾了一下. 主要有2个地方: 1.查看阿里云数据库外网连接地址:打开云数据库RDS-实例列表-管理-数据库连 ...
- 论文阅读 Dynamic Network Embedding by Modeling Triadic Closure Process
3 Dynamic Network Embedding by Modeling Triadic Closure Process link:https://scholar.google.com.sg/s ...
- Tomcat启动失败:java.lang.NoSuchMethodError: org.apache.tomcat.util.res.StringManager.getManager(Ljava/lang/Class;)Lorg/apache/tomcat/util/res/StringManager
项目开发中发现服务器上Tomcat启动失败 开始定位 第一步:打开tomcat日志catalina.log: 2017-07-25 17:02:43,799 [Catalina-startStop-1 ...
- vue运行npm run dev时候,自动打开页面
在config/index.js找到dev:{}里面的autoOpenBrowser: 设置为true,重新npm run dev一次就自动弹出浏览器页面啦!
- client offset scroll 之间的区别
一.client 属性 值 clientWidth 元素被设置的宽度 + padding左右内间距 clientHeight 元素被设置的高度 + padding上下内间距 clientLeft 左 ...
- python PIL 图片素描化
from PIL import Image import numpy as np a = np.asarray(Image.open("D://7.jpg").convert('L ...
- 3.C++逐行读取txt文件数据,利用getline -windows编程
引言:今天学会了getline的用法,顺手编写一个逐行读取txt文件的程序.关于getline的用法可以看我之前的博客:2.C++标准库函数:getline函数 定界流输入截取函数 -zobol的 ...
- JS:相等判断
1.= 赋值运算符 错误写法:a+b = c; 2.== :=== ==判断值是否相等 例: var a = 2; var b = 3; var c = a+b; var d = "2&q ...
- SpringBoot 集成缓存性能之王 Caffeine
使用缓存的目的就是提高性能,今天码哥带大家实践运用 spring-boot-starter-cache 抽象的缓存组件去集成本地缓存性能之王 Caffeine. 大家需要注意的是:in-memeory ...