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 ...
随机推荐
- 网易数帆 Envoy Gateway 实践之旅:坚守 6 年,峥嵘渐显
服务网格成熟度不断提升,云原生环境下流量处理愈发重要, Envoy Gateway 项目于近日宣布开源,"旨在大幅降低将 Envoy 作为 API 网关的使用门槛",引发了业界关注 ...
- 管理订单状态,该上状态机吗?轻量级状态机COLA StateMachine保姆级入门教程
前言 在平常的后端项目开发中,状态机模式的使用其实没有大家想象中那么常见,笔者之前由于不在电商领域工作,很少在业务代码中用状态机来管理各种状态,一般都是手动get/set状态值.去年笔者进入了电商领域 ...
- C++ 获取指定的重载函数地址
刚刚看到一篇博客,说 std::bind 无法绑定正确的重载函数.这里的问题并不是 std::bind 能力不足,而是将函数名传递给 std::bind 时编译器无法取到这个函数的地址(也就是符号,编 ...
- Markdown的使用指南
# Markdown学习 ------ 以下符号均是英文输入法下的 ## 1.标题 几级标题就写 几个#号 加 空格 加 标题内容 就可以 例如: ###加空格加三级标题效果如下 ### 三级标题 # ...
- ExtJS 布局-Center布局(Center layout)
更新记录: 2022年6月12日 检查发布. 2022年6月1日 开始. 1.说明 center布局将子项放置在容器的中心. 2.设置布局方法 在父容器中设置 layout: 'center', // ...
- php个性代码注释
// _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \ ...
- java类的学习
什么是类: 类=属性+方法 属性来源于状态(以变量的形式存在):方法来源于动作: *属性对应的是数据,而数据只能存在变量中. 方法内的变量为局部变量:类体中的变量称为成员变量(也称为属性) java中 ...
- Python-安装lmdb失败-解决方法
使用pip install lmdb 时报错 ERROR: Command errored out with exit status 1: python setup.py egg_info Check ...
- JavaScript做简单的购物车效果(增、删、改、查、克隆)
比如有时候遇到下面这种情况,点击加入购物车,然后在上方的购物车中动态的添加商品以及商品的信息,我们就可以通过JavaScript实现简单的这些操作. 首先我们需要在html文档中,通过css对页面的布 ...
- SAP 实例 6 HTML input
REPORT demo_html_input. CLASS demo DEFINITION. PUBLIC SECTION. CLASS-METHODS main. PRIVATE SECTION. ...