美文网首页
React 新特性Hooks快速上手

React 新特性Hooks快速上手

作者: KaiW | 来源:发表于2019-02-28 20:40 被阅读0次
Hooks

最近看到Kent.C.Dodds大神在博客和视频教程频中繁提到react16.8新特性Hooks,于是想动手体验一下Hooks到底有何神奇之处。

首先什么是Hooks? 详细的介绍可以参考官方doc。 经过一些尝试后,我感受大体上比之前的开发有一下几点提升。

  1. React 组件如果要维护状态需要基于class写组件,class 有一个不好理解的地方就是this,程序一不小心就会有bug。Hooks 用function也可以用组件状态,可以有效避免this这个大坑。

  2. 有经验的react开发者都知道业务逻辑的重用原来都是用HOC,或者Render props模式。但这带来了调试的问题,组件被层层嵌套就是所谓的: 包装地狱 Wrap hell

  3. class组件无论对于机器和人都比function组件更难理解。

既然有那么多优势,接下来用一个实际例子来演示一下。

假设我们要做一个N秒钟后自动消失的组件。

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import "./styles.css";

function useExpire(expireDate) {
  const [shouldRender, setshouldRender] = useState(true);
  useEffect(
    () => {
      console.log(expireDate - Date.now())
      const timeoutId = setTimeout(() => {
        setshouldRender(false);
      }, expireDate - Date.now());

      return () => {
        clearTimeout(timeoutId);
      };
    },
    [expireDate]
  );
  return shouldRender;
}

const One = ({ expireDate }) => {
  return useExpire(expireDate) ? <h2>1秒后消息</h2> : null;
}

const Two = ({ expireDate }) => {
  return useExpire(expireDate) ? <h2>2秒后消息</h2> : null;
}
const App =( )=> {
  
  return (
    <div className="App">
      <h1>Hello Hooks</h1>
     
      <One expireDate={new Date(Date.now() + 1000)} />
      <Two expireDate={new Date(Date.now() + 2000)} />

    </div>
  );
}


const rootElement = document.getElementById("root");
ReactDOM.render(<App />,
 rootElement);

codesandbox演示地址: https://codesandbox.io/s/wkw4k757rk

另外,笔者发现前端社区对hooks已经快速跟进,出现了大量的hooks库如react apollo hooks等。
有兴趣可以查阅 hooks react 库集合网站: https://nikgraf.github.io/react-hooks/

参考:https://daveceddia.com/useeffect-hook-examples/

相关文章

网友评论

      本文标题:React 新特性Hooks快速上手

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