1、useState-自动推导
场景适合:有明确的初始值
import { useState } from "react"
function App() {
const [value,setValue] = useState(false)
const [list,setList] = useState(['111','222'])
const changeList = ()=>{
setList(['111','222','2ee'])
}
const changeValue = ()=>{
setValue(false)
}
return (
<>
this is app{list}
</>
)
}
export default App
2、useState-传递泛型参数
useState本身是一个泛型函数,可以传入具体的自定义类型,
如果初始值没有传参,setUser可以传undefined
import { useState } from "react"
function App() {
type User = {
name:string,
age:number
}
//1、限制useState的初始值的两种写法
// const [User,setUser] = useState<User>({
// name:'jake',
// age:19
// })
const [User,setUser] = useState<User>(()=>{
return {
name:'zhangsa',
age:18
}
})
//2、限制setUser的参数必须满足类型的两种写法
// const changeUser = ()=>{
// setUser({
// name:'lisi',
// age:30
// })
// }
const changeUser = ()=>{
setUser(()=>{
return {
name:'lisi',
age:30
}
})
}
return (
<>
this is app {User.age}
</>
)
}
export default App
3、uesState-初始值是null
当不知道状态的初始值是什么,将useState的初始值设为null是一个常见的作法,可以通过具体类型联合null来做显示注解
import { useState } from "react"
function App() {
type User = {
name:string,
age:number
}
const [user,setUser] = useState<User | null>(null)
const changeUser = () =>{
setUser(null)
setUser({
name:'zhangsan',
age:0
})
}
return (
<>
{/* 为了类型安全,可选链作为守卫,只有类型不为null(不为空值)的时候才进行点运算 */}
this is app {user?.age}
</>
)
}
export default App