《React-Hooks 介绍》

文章目录

  • 什么是Hooks
  • 一眼看完Hooks
      • `State Hook`
      • `Effect Hook`

React v16.7-alpha 版本,推出了一个新的 API 叫做 React-Hooks,它的主要功能是让 function component 可以像 class component 那样,可以处理 state, life-cycle, effect, context 等特性。

相比 class component,react-hooks 代码写起来更加简洁,并且可复用性更高。

什么是Hooks

Hooks是一个新特性提议,它可以让你在不用class的的情况下依然能够使用state和其他的 React 特性

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

useState这个新方法是我们学到的第一个‘Hook’,如果你对Hooks还是没有太多感觉,不要担心,上面的例子只是小试牛刀!
接下来我们会解释为什么要在React中加入Hooks以及Hooks是如何帮你写一个非常棒的应用程序的。


一眼看完Hooks

Hooksbackwards-compatible(向下兼容)的,这一节可以让熟悉react的开发者快速预览一下啊Hooks

State Hook

下面这个例子渲染了一个计数器,当你点击这个按钮的时候数值会增加

import { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

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

声明更多的state变量

在一个component中可以多次使用State Hook

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

Effect Hook

下面这个例子在React更新DOM之后设置了文档标题

import { useState, useEffect } from 'react';

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

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

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

声明更多的state变量

在一个component中可以多次使用State Hook

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

你可能感兴趣的:(react)