将一个界面视为函数V,拥有状态和属性
V = (props, state) => {...}
将UI也视作函数,UI = 界面函数 使用(use)了 hook1、hook2......
UI = V(props, state) useHook1() useHook2() ...
hooks可以大体分为state hook、effect hook和context hook,他们都是通过钩子作用在界面身上的,是用于改变状态、产生作用和改变上下文的一个个函数
如图1所示,作用通过行为来改变状态,再由状态来驱动视图。其中:属性一定是不变的,会改变的仅仅是状态 例如,onClick是视图身上的属性,在这个属性中定义了触发action函数的动作(作用) action函数是一个异步的行为,这个行为改变了F函数所依赖的状态,再由状态驱动视图的改变
import { useXXX } from '...'
const UI = () => {
// 状态
const state = {
a:1,
b:2,
c:3
}
// 行为
const action = async () => {
const res = await fetchData()
state.xxx = res
}
// use state hook
const [count, setCount] = useState(0)
// use effect hook
useEffect(() => {
setTimeOut(() => {
setCount(count+1)
}, 1000)
})
// use other hook
useXXX()
//视图里不要改变状态
//bad: onClick = { () => { state.a = ++state.a } }
return (
//onClick是一个属性
<div onClick={action}>
{a}
{b}
{c}
{count}
</div>
)
}