我是 react 和 TS 的新手,我需要帮助我正在尝试将 useState 与 typescript 一起使用
import React,{useState} from 'react'
interface Count{
count: number
}
const App = () =>{
const [count,setCount] = useState<Count>(
{
count:0
})
return (
<div>
<div>Count <span>{count}</span> </div>
</div>
)
}
export default App;
回答1
应该是 {count.count}
因为 count
是一个对象 ({count:0}
)
<div>Count <span>{count.count}</span> </div>
回答2
您的状态当前是一个对象。这在 react 函数组件中是不常见的(因为您可以根据需要多次调用 useState
),所以除非有理由对对象执行此操作,否则我建议将其设为一个数字:
const [count, setCount] = useState(0);
或使用显式类型:
const [count, setCount] = useState<number>(0);
如果你确实需要你的状态是一个完整的对象,那么确保取出数字并将其放在页面上,而不是完整的对象:
<span>{count.count}</span>