2021-07-17React Hooks

1. React Hooks

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

1.1. 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. useEffect

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

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

created

function FunctionComponent () {
  useEffect(() => {
    // 这个函数只会执行一次
  }, [])
}

updated(watch)

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

destroyed

function FunctionComponent () {
  useEffect(() => {
    return () => {
      // 这个函数会在组件被销毁时执行
    }
  }, [])
}

2. ReactRouter Hooks

2.1. useParams

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

import { useParams } from 'react-router-dom'

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

2.2. useLocation

可以获取路由相关信息

import { useLocation } from 'react-router-dom'

const FuntionComponent = () => {
  const location = useLocation()
}

2.3. useHistory

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

import { useHistory } from 'react-router-dom'

const FuntionComponent = () => {
  const history = useHistory()

  /* 
    history.push('') 可以进行页面跳转
    history.replace("") 跳转页面,会替换最新的记录
    history.go()
   */
}

3. 自定义hooks

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

3.1. useQuery

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

function useQuery () {
  return new URLSearchParams(useLocation().search)
}

useQuery().get('参数')
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值