如何在 React 项目中应用 React 挂钩

简介

在本文中,您将探索React Hooks,这是React最新版本16.8中的一个新特性。React Hooks是函数,作为状态和生命周期方法的模块化替代品。代替类组件,React Hooks允许您构建基于函数的组件。

前提条件

要完成本教程,需要了解Reaction。要了解有关Reaction的更多信息,请参阅如何在React中编程]系列。

分析useState()方法

在类组件中,您可以将REACT导入到一个index.js文件中,并创建一个类对象JustAnotherCounter的实例。您需要添加一个状态和一个函数来更新属性Count

 1[label index.js]
 2import React, { Component } from 'react';
 3
 4class ScoreCounter extends Component {
 5  state = {
 6    count: 0
 7  };
 8
 9  setCount = () => {
10    this.setState({ count: this.state.count + 1 });
11  };
12
13  render() {
14    return (
15      <div>
16        <h1>{this.state.count}</h1>
17
18        <button onClick={this.setCount}>Count Up To The Moon</button>
19      </div>
20    );
21  }
22}

在您的‘render`生命周期方法中,您将返回保存在状态中的值和一个通过每次单击来调用您的函数的按钮。

让我们将您的ScoreCounter类组件作为功能组件进行比较。

使用Reaction Hooks,您可以用更少的代码行将状态和生命周期方法压缩到index.js文件中的一个功能组件中。将useState导入去结构化对象:

 1[label index.js] 
 2import React, { useState } from 'react';
 3
 4function ScoreCounter() {
 5  const [count, setCount] = useState(0);
 6
 7  return (
 8    <div>
 9      <h1>{count}</h1>
10      <button onClick={() => setCount(count + 1)}>Count Up To The Moon</button>
11    </div>
12  );
13}

useState()方法将状态对象分解为一个数组,并为其元素分配调用_钩子_的值。第一个元素是状态,第二个是作为.setState()方法操作的函数。您传递给useState()方法的参数充当初始状态值,这里的数字`0‘作为您的计数器。您可以传入任何数据类型,如数组、对象、字符串和数字作为初始状态值。

每次单击按钮,setCount()函数都会将您的状态作为一个参数传入,该参数以1递增。

现在,您的ScoreCounter函数组件支持较少的语法,有利于代码的可读性。

您也可以在同一个函数中多次使用useState()方法。在您的index.js文件中,导入useState并声明功能组件Login

 1[label index.js]
 2import React, { useState } from 'react';
 3
 4function Login() {
 5  const [username, setUsername] = useState('');
 6  const [password, setPassword] = useState('');
 7
 8  return (
 9    <div className="login">
10      <form>
11        <label>
12            Username: <input value={username} onChange={event => setUsername(event.target.value)}/>
13            <br />
14            Password: <input value={password} onChange={event => setPassword(event.target.value)}/>
15          </label>
16        <button>Submit</button>
17      </form>
18    </div>
19  );
20}

Login功能组件多次使用useState()方法在表单中定义和设置用户名和密码,并概述每个input字段的逻辑。

了解了useState()之后,让我们考虑一下其他的反应钩子方法。

使用useEffect()方法

React Hooks引入了useEffect()方法来替换类组件的生命周期方法ComponentDidMonttComponentDidUpdateComponentWillUnmount。该方法还允许在功能组件中产生副作用,例如更改文档对象模型中的内容和获取数据。每次组件渲染后都会运行useEffect()

让我们将类的生命周期方法调用与功能组件进行比较。

在您的index.js文件中,将useEffect导入您的ScoreCounter组件:

 1[label index.js] 
 2import React, { useState, useEffect } from 'react';
 3
 4function ScoreCounter() {
 5  const [count, setCount] = useState(0);
 6
 7  useEffect(() => {
 8    console.log(count); 
 9    document.title = `Your new score is ${count}`;
10  });
11
12  return (
13    <div>
14      <h1>{count}</h1>
15      <button onClick={() => setCount(count + 1)}>Count Up To The Moon</button>
16    </div>
17  );
18}

这里,useEffect()产生的副作用是登录控制台检查Count中的初始状态值,并更新文档对象模型。

由于useEffect()在组件每次呈现时都会运行,因此您可以设置第二个参数(数组)来存储每个实例,并在值发生更改时调用该方法。

index.js文件中,将空数组作为第二个参数应用到useEffect()方法:

 1[label index.js] 
 2import React, { useState, useEffect } from 'react';
 3
 4function ScoreCounter() {
 5  const [count, setCount] = useState(0);
 6
 7  useEffect(() => {
 8    console.log(count); 
 9    document.title = `Your new score is ${count}`;
10  }, []); 
11}

每次呈现到ScoreCounter组件时,useEffect()方法会将Count的每个实例存储在数组中,如果值与上一次调用不同,则更新组件。在一次调用中,useEffect()结合了ComponentDidMonttComponentDidUpdate生命周期方法中的功能。

要模拟ComponentWillUnmount生命周期方法,请在您的index.js文件中的useEffect()方法中返回一个函数:

 1[label index.js] 
 2import React, { useState, useEffect } from 'react';
 3
 4function ScoreCounter() {
 5  const [count, setCount] = useState(0);
 6
 7  useEffect(() => {
 8    console.log(count); 
 9    document.title = `Your new score is ${count}`;
10
11    return () => console.log(`Component is unmounted`);
12  }, []); 
13}

通过声明并返回一个匿名函数,useEffect()方法在一次调用中卸载了一个组件,这里使用console.log来检查其状态。

要获取数据,请在useEffect()中传入fetch,从外部接口获取信息。

在您的index.js文件中,导入useStateuseEffect。声明一个GitHubUsers函数组件,并在useEffect的Body中传入fetch

 1[label index.js]
 2import React, { useState, useEffect } from 'react';
 3
 4function GitHubUsers() {
 5  const [user, setUsers] = useState([]);
 6
 7  useEffect(() => {
 8    fetch('https://api.github.com/users')
 9      .then(response => response.json())
10      .then(data => {
11        setUsers(data); // set users in state
12      });
13  }, []);

请注意,第二个参数设置为空数组。这是为了通知useEffect()运行一次。useEffect()方法会调用fetch来调用GitHub API,并将响应设置为json对象。

调用成功后,在您的GitHubUsers组件中包含一条返回语句,以迭代数据并输出GitHub用户信息:

 1[label index.js]
 2  return (
 3    <div className="section">
 4      {users.map(user => (
 5        <div key={user.id} className="card">
 6          <h5>{user.login}</h5>
 7        </div>
 8      ))}
 9    </div>
10  );
11}

useEffect()方法在一次调用中使用类组件的所有三个生命周期方法中的功能,以登录到控制台、更新文档对象模型以及从外部API获取数据。

结论

useState()useEffect()方法是对Reaction库的强大添加。现在使用Reaction Hooks,您可以用更短的代码行最大限度地利用状态和生命周期方法来实现功能组件的最大化。

有关Reaction钩子的更多信息,请查看How to Manage State with Hooks on React Components]一文。

Published At
Categories with 技术
Tagged with
comments powered by Disqus