美文网首页
为什么定义React hooks函数要以use开头

为什么定义React hooks函数要以use开头

作者: jjjkkkhhhggg | 来源:发表于2020-08-15 15:38 被阅读0次

官方的解释

图1: React官方文档解释(英文版)
图2: React官方文档解释(中文翻译版)

从UI的层面解释

将一个界面视为函数V,拥有状态和属性

V = (props, state) => {...}

我们可以将UI也视作函数

UI = 界面函数 使用(use)了 hook1、hook2...

UI = V(props, state) useHook1() useHook2() ...

hooks可以大体分为state hook、effect hook和context hook,他们都是通过钩子作用在界面身上的,是用于改变状态、产生作用和改变上下文的一个个函数

额外:UI是如何被渲染的

如图3 所示

作用通过触发行为来改变状态,再由状态来驱动视图。其中:视图上的属性[一定?]是不变的,会改变的仅仅是状态

图3: 重新定义UI from 腾讯课堂

例如,onClick是视图身上的属性,在这个属性中定义了触发action行为的作用(动作)
action函数是一个异步的行为,这个行为改变了V函数所依赖的状态,再由状态驱动视图的改变

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>
    )
}

相关文章

  • 为什么定义React hooks函数要以use开头

    官方的解释 从UI的层面解释 将一个界面视为函数V,拥有状态和属性 我们可以将UI也视作函数 UI = 界面函数 ...

  • Deep Dive React 3 React Hooks

    React Hooks allow us to use React features without writin...

  • React Hooks

    React Hooks Hooks其实就是有状态的函数式组件。 React Hooks让React的成本降低了很多...

  • React Hook - 官方文档 - One

    Hooks They let you use state and other React features wit...

  • react-hooks

    前置 学习面试视频 总结react hooks react-hooks react-hooks为函数组件提供了一些...

  • React Hooks的使用限制

    React Hooks的使用限制 只能用于函数组件或自定义Hooks中 不能写在条件语句中 不能写在函数组件或自定...

  • React hooks(1)

    1. 什么是hooks A way to use state and other React features w...

  • React Hooks && Hox

    一、React Hooks 1.useState状态钩子 const [count,setCount] = use...

  • 2020-09-08

    React Hooks react Hooks就是用函数的形式代替原来的继承类的形式,并且使用预函数的形式管理st...

  • React Hooks 入门

    目录 什么是 React Hooks? 为什么要创造 Hooks? Hooks API 一览 Hooks 使用规则...

网友评论

      本文标题:为什么定义React hooks函数要以use开头

      本文链接:https://www.haomeiwen.com/subject/kcnodktx.html