美文网首页
React-Hook的使用

React-Hook的使用

作者: 諾城 | 来源:发表于2020-08-20 16:22 被阅读0次

函数式组件在不编写class的情况下使用state以及其他的React特性(比如生命周期)

一、Hooks结合函数式组件使用(useState)

通过一个计数器案例,来对比一下class组件和函数式组件结合hooks的对比:
1、class组件实现:

import React, { PureComponent } from 'react';

class HookTest extends PureComponent {

  constructor(props){
    super(props)

    this.state = {
      count: 0
    }
    this.addCount = this.addCount.bind(this)
  }
  
  render() {
    return (
      <div>
        <h2>{this.state.count}</h2>
        <button onClick={this.addCount}>增加</button>
      </div>
    );
  }

  addCount(){
    this.setState({
      count: this.state.count+1
    })
  }
}

export default HookTest;

2、函数式组件结合hooks使用:

import React, { useState } from 'react';

function HookTest(){

 const [count, setCount] = useState(0)   // ES6结构

  return (
    <div>
      <h2>{count}</h2>
      <button onClick={()=>setCount(count+2)}>增加</button>
    </div>
  )
}

export default HookTest

通过上面对比发现,函数式组件结合hooks使用让代码看起来更加整齐。
解析:const [count, setCount] = useState(0)
1、其中count是参数,setCount是设置参数count的函数;
2、useState是一个函数,返回一个数组,可结构成一个参数和设置参数的函数,有一个唯一的参数,设置的是参数count的初始值。

3、在一个函数组件中定义多个变量和复杂变量(数组、对象):

import React, { useState } from 'react';

function HookTest(){

  const [count, setCount]     = useState(0)   // ES6结构
  const [list, setList]       = useState(['A', 'B', 'C'])
  const [person, setPerson]   = useState({'name': 'Jack'})

  return (
    <div>
      <h2>{count}</h2>
      <h2>{person.name}-{person.age}</h2>
      <ul>
        {
          list.map((item, index) => {
            return (
              <li key={index}>{item}</li>
            )
          })
        }
      </ul>
      <button onClick={()=>setCount(count+2)}>增加数字</button>
      <button onClick={()=>setList([...list, 'D'])}>修改列表</button>
      <button onClick={()=>setPerson({...person, name: 'Lucy', age: 19})}>修改对象</button>
    </div>
  )
}

export default HookTest

二、 Effect Hook的使用(useEffect)

1、Effect Hook 类似于class中生命周期的功能

function Index(){

  // useEffect页面初始化使用,相当于componentDidMount
  useEffect(() => {
    console.log('index in');

    // return在页面销毁时候调用,相当于componentWillUnmount
    return ()=>{
      console.log('index out'); 
    }
  }, [])
  return <h2>index page</h2>
}

2、使用多个Effect
使用Hook的其中一个目的就是解决class中生命周期经常将很多的逻辑放在一起的问题:
比如网络请求、事件监听、手动修改DOM,这些往往都会放在componentDidMount中;
使用Effect Hook,我们可以将它们分离到不同的useEffect中:

import React, { useEffect } from 'react';

export default function MultiUseEffect() {
 useEffect(() => {
   console.log("网络请求");
 });

 useEffect(() => {
   console.log("修改DOM");
 })

 useEffect(() => {
   console.log("事件监听");

   return () => {
     console.log("取消监听");
   }
 })

 return (
   <div>
     <h2>MultiUseEffect</h2>
   </div>
 )
}

Hook 允许我们按照代码的用途分离它们, 而不是像生命周期函数那样:
React 将按照 effect 声明的顺序依次调用组件中的每一个 effect;

3、 Effect性能优化
默认情况下,useEffect的回调函数会在每次渲染时都重新执行,但是这会导致两个问题:
某些代码我们只是希望执行一次即可,类似于componentDidMount和componentWillUnmount中完成的事情;(比如网络请求、订阅和取消订阅);
另外,多次执行也会导致一定的性能问题;
我们如何决定useEffect在什么时候应该执行和什么时候不应该执行呢?
useEffect实际上有两个参数:
参数一:执行的回调函数;
参数二:该useEffect在哪些state发生变化时,才重新执行;(受谁的影响)
我们来看下面的一个案例:
在这个案例中,我们修改show的值,是不会让useEffect重新被执行的;

import React, { useState, useEffect } from 'react';

export default function EffectPerformance() {
  const [count, setCount] = useState(0);
  const [show, setShow] = useState(true);

  useEffect(() => {
    console.log("修改DOM");
  }, [count])

  return (
    <div>
      <h2>当前计数: {count}</h2>
      <button onClick={e => setCount(count + 1)}>+1</button>
      <button onClick={e => setShow(!show)}>切换</button>
    </div>
  )
}

但是,如果一个函数我们不希望依赖任何的内容时,也可以传入一个空的数组 []

三、Context Hook的使用(useContext)

Context Hook可以让我们通过Hook来直接获取某个Context的值:

const value = useContext(MyContext);

在App.js中使用Context:

import React, { createContext } from 'react';

import ContextHook from './04_useContext使用/01_ContextHook';

export const UserContext = createContext();
export const ThemeContext = createContext();

export default function App() {
  return (
    <div>
      <UserContext.Provider value={{name: "why", age: 18}}>
        <ThemeContext.Provider value={{color: "red", fontSize: "20px"}}>
          <ContextHook/>
        </ThemeContext.Provider>
      </UserContext.Provider>
    </div>
  )
}

在对应的函数式组件中使用Context Hook:

import React, { useContext } from 'react'
import { UserContext, ThemeContext } from '../App'

export default function ContextHook() {
  const user = useContext(UserContext);
  const theme = useContext(ThemeContext);
  console.log(user);
  console.log(theme);

  return (
    <div>
      ContextHook
    </div>
  )
}

四、关于useReducer Hook的使用 (useReducer)

useReducer仅仅是useState的一种替代方案:

  • 在某些场景下,如果state的处理逻辑比较复杂,我们可以通过useReducer来对其进行拆分;
  • 或者这次修改的state需要依赖之前的state时,也可以使用;

单独创建一个reducer/counter.js文件:

export function counterReducer(state, action) {
  switch(action.type) {
    case "increment":
      return {...state, counter: state.counter + 1}
    case "decrement":
      return {...state, counter: state.counter - 1}
    default:
      return state;
  }
}

home.js文件:

import React, { useReducer } from 'react'
import { counterReducer } from '../reducer/counter'

export default function Home() {
  const [state, dispatch] = useReducer(counterReducer, {counter: 100});

  return (
    <div>
      <h2>当前计数: {state.counter}</h2>
      <button onClick={e => dispatch({type: "increment"})}>+1</button>
      <button onClick={e => dispatch({type: "decrement"})}>-1</button>
    </div>
  )
}

profile.js文件(创建另外一个profile.js也使用这个reducer函数):

import React, { useReducer } from 'react'
import { counterReducer } from '../reducer/counter'

export default function Profile() {
  const [state, dispatch] = useReducer(counterReducer, {counter: 0});

  return (
    <div>
      <h2>当前计数: {state.counter}</h2>
      <button onClick={e => dispatch({type: "increment"})}>+1</button>
      <button onClick={e => dispatch({type: "decrement"})}>-1</button>
    </div>
  )
}

通过执行可以发现,home.js文件和profile.js文件在使用的时候,counter并不会共享,也就是说home文件中修改counter的值不会影响profile中counter的值,同理修改profile文件中counter也是。
所以,useReducer只是useState的一种替代品,将复杂的useState拆分到不同的文件中,并不能替代Redux。

相关文章

  • react-hook

    react-hook

  • React-Hook的使用

    函数式组件在不编写class的情况下使用state以及其他的React特性(比如生命周期) 一、Hooks结合函数...

  • 实用的react hook

    接触react-hook已经很久了,用了之后,发现真的很强大,记录一下最近使用的想法 useState 首先接触到...

  • react-hook

    useState的用法 useEffect 代替常用生命周期函数 表示 componentDidMonut 和 c...

  • React-Hook

    react hook必须在react16.8版本以上才能使用 1.useState 官网对useEffect的介绍...

  • react-hook

    参考:https://zhuanlan.zhihu.com/p/79127886 //对react hook其中的...

  • useState原理以及其它react-hook的使用

    前言 自react16.8发布了正式版hook用法以来,我们公司组件的写法逐渐由class向函数式组件+hook的...

  • React-Hook快速入门(一)

    一、React介绍 温馨提醒:想要获取更好的观看效果,可以点击查看本篇文章的原文档(React-Hook快速入门(...

  • React-Hook 应用

    Hook 是 react 16.8 推出的新特性,具有如下优点:Hook 使你在无需修改组件结构的情况下复用状态逻...

  • React-Hook:useState

    1. 使用 因为react是函数式编程,useState函数接收一个初始化参数initialState,其返回值用...

网友评论

      本文标题:React-Hook的使用

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