Reactjs 使用React钩子时的Typescript错误

Reactjs 使用React钩子时的Typescript错误,reactjs,typescript,react-hooks,ionic4,Reactjs,Typescript,React Hooks,Ionic4,我尝试在Ionic应用程序中使用react-useState、useRef和typescript挂钩,并且在尝试访问对象属性时不断出现愚蠢的typescript错误 const [ matrix, updateMatrix ] = useState([]); updateMatrix([['cell1', 'cell2', 'cell3'], ['cell4', 'cell5', 'cell6']]) 在上面的代码中,我得到 “类型‘string’不可分配给类型‘never’” 在上面的代码中

我尝试在Ionic应用程序中使用react-useState、useRef和typescript挂钩,并且在尝试访问对象属性时不断出现愚蠢的typescript错误

const [ matrix, updateMatrix ] = useState([]);
updateMatrix([['cell1', 'cell2', 'cell3'], ['cell4', 'cell5', 'cell6']])
在上面的代码中,我得到

“类型‘string’不可分配给类型‘never’”

在上面的代码中,我得到basketEl.current的对象可能为“null”。即使我把

if (basketEl.current !== null) {
错误仍然存在。
有趣的是,如果我不使用钩子和react类,类型脚本错误就会消失。修复ts错误需要很多时间,我放弃了,开始使用类。也许我用错钩子了?是否有人在一起使用hook和typescript时遇到同样的问题?

您必须指定状态的确切类型,因为基于默认值,它们是不明确的

正确代码:

const [ matrix, updateMatrix ] = useState<string[]>([]);

const basketEl = useRef<Element>(null);
const[matrix,updateMatrix]=useState([]);
const basketEl=useRef(null);

const[matrix,updateMatrix]=useState([])

您是否尝试过此操作,因为
basketEl
为空,因此无法调用
basketEl.current
。首先,当组件装载时,必须在
useffect
中调用它。其次,typescript的错误,您可以这样修复:

useEffect(()=>{
  if(basketEl !== null && basketEl.current !== null){
     console.log(basketEl.current.getBoundingClientRect())
  }
}, [basketEl])

请尝试一下,我确信它工作得很好

为什么在使用typescript时不键入钩子?对于ref,现在我有一个ts错误
Type'RefObject'不能分配给Type'string |((实例:HTMLDivElement | null)=>void)| RefObject | null | undefined'。类型“REOBJECT”不可分配给类型“REOBJECT”。类型“Element”缺少类型“HtmlDevice”中的以下属性:align、accessKey、accessKeyLabel、autocapitalize和108更多。ts(2322)
当assign ref
时,我从react网站以分配null为例。您是否尝试过
useRef(null)
useEffect(()=>{
  if(basketEl !== null && basketEl.current !== null){
     console.log(basketEl.current.getBoundingClientRect())
  }
}, [basketEl])