React Hook概述

作者: Nian糕 | 来源:发表于2020-04-21 08:33 被阅读0次
Unsplash

Hook 是什么?Hook 是 React 16.8 的新增特性,它可以让你在不编写 class 的情况下“钩入” React 的特性,例如,useState 是允许你在 React 函数组件中添加 state 的 Hook

1. State Hook

useState 是一种新方法,它与 class 里面的 this.state 提供的功能完全相同。一般来说,在函数退出后变量就会“消失”,而 state 中的变量会被 React 保留,useState() 方法里面唯一的参数就是初始 state,我们可以使用 numberstring 对其进行赋值,其返回值为当前的 state 以及更新 state 的函数

// src/comments/LikeButton.js
import React, { useState } from 'react'

// 函数型组件
const LikeButton = () => {
  const [ like, setLike ] = useState(0)
  console.log(useState(0))
  return (
  <button onClick={() => {setLike(like + 1)}}>
    喜欢数 {like}
  </button>
  )
}

export default LikeButton

随后在 App.js 中引入该组件,效果如下图所示

LikeButton组件

上面的 Hook 代码通过 class 组件进行编写,如下所示

class LikeButton extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      like: 0
    };
  }

  render() {
    return (
      <button onClick={() => this.setState({ like: this.state.like + 1 })}>
        喜欢数 {this.state.like}
      </button>
    );
  }
}

2. Effect Hook

在 React 更新 DOM 之后我们如果想要运行一些额外的代码,比如发送网络请求,手动变更 DOM,记录日志,订阅外部数据源等等,我们就会使用到 Effect Hook,类似于 Vue 中的 nextTick 方法

而在 React 的 class 组件中,我们会把同样的操作放到 componentDidMountcomponentDidUpdate 函数中,需要在两个生命周期函数中编写重复的代码

componentDidMount() {
  document.title = `You clicked ${this.state.like} times`;
}
componentDidUpdate() {
  document.title = `You clicked ${this.state.like} times`;
}

使用 useEffect 执行相同的操作,代码如下所示

const LikeButton = () => {
  const [ like, setLike ] = useState(0)
  
  useEffect(() => {
    document.title = `You clicked ${like} times`;
  })
  
  return (
  <button onClick={() => {setLike(like + 1)}}>
    喜欢数 {like}
  </button>
  )
}
useEffect 组件

useEffect 在默认情况下,在第一次渲染之后以及每次更新之后都会执行,只需要知道 effect 发生在渲染之后,而不用再去考虑是挂载还是更新状态,Effect 组件在需要清除的时候,可以通过返回一个函数进行清除,React 将会在执行清除操作时调用它

// comments/MouseTracker.js
import React, { useState, useEffect } from 'react'

function MouseTracker() {
  const [ positions, setPositions ] = useState({x: 0, y: 0})
  useEffect(() => {
    const updateMouse = e => {
      setPositions({x: e.clientX, y: e.clientY})
    }
    document.addEventListener('click', updateMouse)
    return () => {
      document.removeEventListener('click', updateMouse)
    }
  })
  return (
    <p>X: {positions.x}, Y: {positions.y}</p>
  )
}

export default MouseTracker

如果某些特定值在两次重渲染之间没有发生变化,可以传递数组作为 useEffect 的第二个可选参数,就能够通知 React 跳过对 effect 的调用

useEffect(() => {
  document.title = `You clicked ${like} times`;
}, [count]); // 仅在 like 更改时更新

关于 Hook 的更多使用方法,可在 useHooks 中查看相关例子

3. 自定义 Hook

自定义 Hook,就是将组件逻辑提取到可重用的函数中

// hooks/useURLLoader.js
import { useState, useEffect } from 'react'
import axios from 'axios'

const useURLLoader = (url) => {
  const [data, setData] = useState(null)
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    setLoading(true)
    axios.get(url).then(result => {
      setData(result.data)
      setLoading(false)
    })
  }, [url])
  return [data, loading]
}

export default useURLLoader
// App.js
const CatShowWithHook = () => {
  const [ category, setCategory ] = useState('1')
  const [ data, loading ] = useURLLoader(`https://api.thecatapi.com/v1/images/search?limit=1&category_ids=${category}`)
  return (
    <>
      <button onClick={() => { setCategory('1') }}>帽子猫</button>
      <button onClick={() => { setCategory('5') }}>盒子猫</button>
      {loading ? <p>新猫咪读取中</p>
       : <img src={data && data[0].url} alt="cat" style={{width: 300}} />
      }
    </>
  )
}
自定义 Hook

参考资料
React 官网 - 使用 State Hook
React 官网 - 使用 Effect Hook
React 官网 - 自定义 Hook

本篇的内容到这里就全部结束了,源码我已经发到了 GitHub React_02 上了,有需要的同学可自行下载

End of File

行文过程中出现错误或不妥之处在所难免,希望大家能够给予指正,以免误导更多人,最后,如果你觉得我的文章写的还不错,希望能够点一下喜欢关注,为了我能早日成为简书优秀作者献上一发助攻吧,谢谢!^ ^

相关文章

  • React Hook 概述

    官方文档:https://react.docschina.org/docs/hooks-intro.html[ht...

  • React Hook概述

    Hook 是什么?Hook 是 React 16.8 的新增特性,它可以让你在不编写 class 的情况下“钩入”...

  • react 16.7 hook概述

    之前我们介绍了使用hooks的原因,在开始介绍api之前,现在我们先来整体的预览下这些api。从上篇的介绍可以知道...

  • React hook 10种 Hook

    React hook 10种 Hook (详细介绍及使用) React Hook是什么?React官网是这么介绍的...

  • React 初探之 Hook

    概述 Hook 使你在非 class 的情况下可以使用更多的 React 特性。Hook 是一些可以在函数组件里钩...

  • 学习react hook的总结

    react16推出了react hook,react hook使得functional组件拥有了class组件的一...

  • react-hook-form使用

    官网地址:https://react-hook-form.com/[https://react-hook-form...

  • react hook介绍

    react hook是什么 react hook是react中引入新特性,它可以让react函数组件也拥有状态;通...

  • React Hook介绍与使用心得

    关于React Hook React Hook 对于React来说无疑是一个伟大的特性,它将React从类组件推向...

  • React Hook

    Through 4 questions introduce React Hook What is Hook? In...

网友评论

    本文标题:React Hook概述

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