当我们用一个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 = () => { //相关文章
- 解决React报错The tag is unrecognized in this
- 解决React报错Style prop value must be an object
- vue3中如何使用ref和reactive定义和修改响应式数据(最
- 解决React报错useNavigate() may be used only i
- React高阶组件使用教程详解
- react component changing uncontrolled input报错解
- 绝地求生运行游戏BattlEye Launcher报错怎么办
- React组件实例三大核心属性State props Refs详解
- React组件的生命周期深入理解分析
- React组件通信实现流程详解
- React中的Hooks路由跳转问题