使用规则:
- 只能在组件中或者其他自定义Hook函数中调用
- 只能在组件的顶层调用,不能嵌套在 if、for、其他函数中
import { useState } from "react"
// 封装函数
function useToggle(){
const [show,setShow] = useState(true);
const toggle = ()=> setShow(!show)
return {
show,toggle
}
}
// const [num,setNum] = useState(0);//报错原因: 只能在组件(function)中使用
function App(){
const { show,toggle } = useToggle();
if( Math.random() > 0.5){
// const [num,setNum] = useState(0);//报错原因:不能在条件判断中使用,for循环中也不可以
}
return (
<div>
<button onClick={toggle}>toggle切换</button>
{ show && <div>显示、隐藏div</div>}
</div>
)
}
export default App