• react hook


    在React中有自带的hooks,也可以自己定义自定义hooks,所有的hooks都是以use开头–useXxx

    useState

    解决了React函数组件中没有状态的问题

    const FuntionComponent = () => {
      // 如果想要设置相关的变量存储数据使用useState。useState调用后返回的是一个数组
      // state 和 setState是自定义的名字 例如: a setA b setB
      const [state, setState] = useState("默认值")
      return (
        <div>
          {state}
          <button onClick={() => setState('新的数据')}></button>
        </div>
      )
    }
    export default FunctionComponent
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    useEffect

    这个hook包含了created updated destroyed三个生命周期钩子函数

    这个hook在一个组件中可以调用多次,所以尽可能将不同的请求放在不同的useEffect

    created

    function FunctionComponent () {
      useEffect(() => {
        // 这个函数只会执行一次
      }, [])
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    updated(watch)

    function FunctionComponent () {
      useEffect(() => {
        // 一旦数组中的值发生了改变,则会触发函数
      }, [相关state的名字, 可以写多个])
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    destroyed

    function FunctionComponent () {
      useEffect(() => {
        return () => {
          // 这个函数会在组件被销毁时执行
        }
      }, [])
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    ReactRouter Hooks

    useParams

    用来获取动态路由参数(vue this.$router.params)

    import { useParams } from ‘react-router-dom’

    const FuntionComponent = () => {
      // 这个参数名和设置的动态路由的参数名一致 useParams调用后就是一个对象
      const { 参数名 } = useParams()
    }
    
    • 1
    • 2
    • 3
    • 4

    useLocation

    可以获取路由相关信息

    import { useLocation } from 'react-router-dom'
    
    const FuntionComponent = () => {
      const location = useLocation()
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    useHistory

    可以控制路由的跳转(相当于vue的编程式导航)

    import { useHistory } from 'react-router-dom'
    
    const FuntionComponent = () => {
      const history = useHistory()
    
      /
        history.push('') 可以进行页面跳转
        history.replace("") 跳转页面,会替换最新的记录
        history.go()
       /
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    自定义hooks

    react允许我们自己定义相关的hook,但是需要已 use 开头

    useQuery

    我们自定义的hook可以用来获取query参数

    function useQuery () {
      return new URLSearchParams(useLocation().search)
    }
    
    useQuery().get('参数')
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    HTML学习(标签)
    彻底了解HTTP模块
    java项目之社区互助平台(ssm+vue)
    博途PLC 1200/1500PLC ModbusTcp通信之状态机编程
    win共享文件进不去
    Netty简介及简单客户端/服务端示例代码
    教会你在python进行代理的方式
    什么是SpringBoot自动配置
    一款支持功能安全车规级 线性PMIC稳压器 NCV4274CDS50R4G 解决方案:高效率、更智能、强功能安全
    CTFHUB ICS(2)
  • 原文地址:https://blog.csdn.net/z18237613052/article/details/126052135