自定义hooks、公共方法和自定义hook的区别、useMemo |
您所在的位置:网站首页 › hooks使用规则 › 自定义hooks、公共方法和自定义hook的区别、useMemo |
前言
当我们想在两个函数之间共享逻辑时,我们会把它提取到第三个函数中。而组件和 Hook 都是函数,所以也同样适用这种方式。 什么是hooks,如何使用。推荐文章: react-hooks如何使用? 玩转react-hooks,自定义hooks设计模式及其实战 规则 定义 Hook 是一个函数,其名称以 “use” 开头,函数内部可以调用其他的 Hook。只在最顶层使用 Hook不要在循环,条件或嵌套函数中调用 Hook只在 React 函数中调用 Hook,不要在普通的 JavaScript 函数中调用 Hook 注意 自定义 Hook 是一种自然遵循 Hook 设计的约定,而并不是 React 的特性。自定义 Hook 必须以 “use” 开头吗?必须如此。这个约定非常重要。不遵循的话,由于无法判断某个函数是否包含对其内部 Hook 的调用,React 将无法自动检查你的 Hook 是否违反了 Hook 的规则。在两个组件中使用相同的 Hook 会共享 state 吗?不会。自定义 Hook 是一种重用状态逻辑的机制(例如设置为订阅并存储当前值),所以每次使用自定义 Hook 时,其中的所有 state 和副作用都是完全隔离的。自定义 Hook 如何获取独立的 state?每次调用 Hook,它都会获取独立的 state。在我们在编写自定义hooks的时候,要特别~特别~特别关注的是传进去什么,返回什么。返回的东西是我们真正需要的。 实例日期格式化 function useTimeFormate(time) { let date = typeof time === 'string' ? new Date(time) : time let year = date.getFullYear() let tempMonth = date.getMonth() + 1 let month = tempMonth > 9 ? tempMonth : '0' + tempMonth let tempDay = date.getDate() let day = tempDay > 9 ? tempDay : '0' + tempDay console.log(1) return year + '-' + month + '-' + day } export default useTimeFormate import {useState} from "react" import useTimeFormate from "../../hooks/time"; function Home() { let [num, setNum] = useState(0) let time = useTimeFormate("2021-11-30") return ( 日期格式化:{time} 数字是:{num} useMemo } from "react" function useTimeFormate(time) { return useMemo(() => { let date = typeof time === 'string' ? new Date(time) : time let year = date.getFullYear() let tempMonth = date.getMonth() + 1 let month = tempMonth > 9 ? tempMonth : '0' + tempMonth let tempDay = date.getDate() let day = tempDay > 9 ? tempDay : '0' + tempDay console.log(1) return year + '-' + month + '-' + day }, [time]) }执行结果:
|
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |