18

[React]Hook初探

 4 years ago
source link: http://www.cnblogs.com/liuju/p/12633624.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Hook是什么

Hook是React从16.8开始支持的特性,使用Hook可以在不使用class时使用state

Hook支持在不需要修改组件状态的情况下复用逻辑状态,从而解决使用render prop和高阶组件产生的代码结构复杂的问题

Hook可以解决在class中因为组件在生命周期函数内分散处理导致的逻辑混乱。

Hook可以解决在class中this的复杂问题。

Hook的结构

State Hook

在通过state进行状态管理时,我们会使用contructor()构造器来初始化state,使用setState()更新state的状态

在Hook里,不再使用以上的两种方法,将会使用

const [name,setName]=useState(defaultValue);

这样的方法进行对状态进行管理。

UseState将会被调用来为函数组件添加state,一个useState方法将会返回一对值(一个数组),一个当前状态和更新这个当前状态的函数,可以在组件的其他地方调用这个更新函数。

这对返回值使用数组解构。

一个useState语句将会创造一个状态。

Effect Hook

我们可以把useEffect看作是componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。

useEffect的第二个可选参数是判断是否执行该函数,如果第二个参数在重渲染的时候没有发生改变,将会跳过这个当前的useEffect。

如果第二个参数是一个空数组([]),effect将只会在组件挂载和卸载时执行,然而这种操作存在风险,具体的见文档中的 Hook/FAQ :在依赖列表中省略函数是否安全?

一个简单的例子

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

function Example() {
  const [count, setCount] = useState(0);

  // 相当于 componentDidMount 和 componentDidUpdate:
  useEffect(() => {
    // 使用浏览器的 API 更新页面标题
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

在这个例子中,声明了一个名为count的状态,在每次点击button时,通过事件处理将会使count+1,在useEffect函数中,使用浏览器的API将count显示。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK