React Hooks入门

React Hooks are a great new feature in React 16.8. Hooks are a feature that you’ll end up using every single day of your React development. Hooks are useful because they enable more features for developers. If you want to use state or lifecycle methods you would normally have to change to using React.Component and classes. Hooks let us use these features in functional components.

React Hooks是React 16.8中的一个很棒的新功能。 挂钩是您将在React开发的每一天中最终使用的功能。 钩子很有用,因为它们为开发人员启用了更多功能。 如果要使用状态或生命周期方法,通常必须更改为使用React.Component和类。 挂钩使我们可以在功能组件中使用这些功能。

React的状态钩 (React’s State Hook)

Let’s say we have a component like this:

假设我们有一个像这样的组件:

组件状态 (State in Components)
import React, { Component } from 'react';

class JustAnotherCounter extends Component {
  state = {
    count: 0
  };

  setCount = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      

{this.state.count}

); } }

With React Hooks, we are a able to condense that class into this functional component:

使用React Hooks,我们可以将该类浓缩为以下功能组件:

具有功能组件的状态和useState (State with Functional Components and useState)
import React, { useState } from 'react';

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

  return (
    

{count}

); }

Notice how the functional component streamlines our code.

注意功能组件如何简化我们的代码。

useState()语法 (useState() syntax)

You may be unfamiliar with the line with the useState() syntax. This uses destructuring assignment for arrays. This is similar to how we would pull props out an object with object destructuring.

您可能不熟悉useState()语法。 这将对数组使用解构分配 。 这类似于我们通过object destructuring将道具拉出object destructuring

Let’s compare object destructuring to array destructuring to see why the latter is helpful.

让我们将对象分解与数组分解进行比较,以了解后者为何有用。

对象分解 (Object Destructuring)
const users = { admin: 'chris', user: 'nick' };

// grab the admin and user but rename them to SuperAdmin and SuperUser
const { admin: SuperAdmin, user: SuperUser } = users;

Object destructuring requires more writing to grab a variable and rename it. With array destructuring we just name variables as we get them out of the array. First variable is the first item in the array.

对象解构需要更多的编写来获取变量并将其重命名。 使用数组解构时,只要将变量从数组中取出就可以命名。 第一个变量是数组中的第一项。

阵列解构 (Array Destructuring)
// array destructuring
const users = ['chris', 'nick'];

// grab in order and rename at the same time
const [SuperAdmin, SuperUser] = users;

useState gives us two variables and we can name our two variables whatever we want. Just know that:

useState给了我们两个变量,我们可以随意命名两个变量。 只是知道:

  1. The first variable is the value. Similar to this.state

    第一个变量是value 。 类似于this.state

  2. The second variable is a function to update that value. Similar to this.setState

    第二个变量是更新该值的函数 。 类似于this.setState

The final part to useState is the argument that we pass to it. The useState argument is the initial state value. In the case of our counter, we started at 0.

useState的最后一部分是我们传递给它的参数。 useState参数是初始状态值。 对于计数器,我们从0开始。

The React Hooks intro gives a good section on this: Classes confuse both people and machines. The gist is classes can sometimes be confusing and can be written any number of ways. Dive into somebody else’s project and you could be in for a world of different syntax and style choices. Note that there are no plans to remove classes support. We just have another way to code

React Hooks的介绍部分对此做了很好的介绍: 类使人和机器都感到困惑 。 要点是,类有时可能会造成混淆,并且可以用多种方式编写。 深入研究其他人的项目,您可能会遇到一个不同的语法和样式选择的世界。 请注意,没有计划删除类支持。 我们还有另一种编码方式

By allowing classes to be converted into smaller functional components, we can even further break out parts of our application into smaller and more focused components.

通过允许将类转换为较小的功能组件,我们甚至可以进一步将应用程序的各个部分分解为较小且更集中的组件

使用多个状态挂钩 (Using Multiple State Hooks)

We can even use useState() multiple times in the same function.

我们甚至可以在同一函数中多次使用useState()

import React, { useState } from 'react';

function AllTheThings() {
  const [count, setCount] = useState(0);
  const [products, setProducts] = useState([{ name: 'Surfboard', price: 100 }]);
  const [coupon, setCoupon] = useState(null);

  return 
{/_ use all those things here _/}
; }

React的效果钩 (React’s Effect Hook)

The State Hook allows us to use state in React functional components. This gets us a step closer to using functional components over class components. The next part of moving to functional components is lifecycle methods. Effects are similar to componentDidMount, componentDidUpdate, and componentWillUnmount.

State Hook允许我们在React功能组件中使用state 。 这使我们比使用类组件更接近使用功能组件。 转向功能组件的下一部分是生命周期方法。 效果类似于componentDidMountcomponentDidUpdatecomponentWillUnmount

This is what the Effect Hook is for. Side-effects are things you want your application to make like:

这就是效果钩的作用。 副作用是您希望应用程序做出的事情:

  • Fetching data

    取得资料
  • Manually changing the DOM (document title)

    手动更改DOM(文档标题)
  • Setting up a subscription

    设置订阅

Effects will run after every render, including the first render.

效果将在每个渲染(包括第一个渲染)之后运行。

Let’s compare a class to a functional component:

让我们将类与功能组件进行比较:

import React, { Component } from 'react';

class DoSomethingCrazy extends Component {
  componentDidMount() {
    console.log('i have arrived at the party!');
    document.title = 'preesent';
  }

  render() {
    return 
stuff goes here
; } }

When using the the Effect Hook, we use useEffect():

使用效果挂钩时,我们使用useEffect()

function DoSomethingCrazy() {
  useEffect(() => {
    console.log('i have arrived at the party!');
    document.title = 'preesent';
  });

  return 
stuff goes here
; }

useEffect() is similar to componentDidMount and componentDidUpdate.

useEffect()componentDidMountcomponentDidUpdate相似。

仅当发生变化时才运行效果挂钩 (Running an Effect Hook only when something changes)

Since useEffect() runs every time a component renders, we can get it to only run once on mount. The Effect Hook can take a second argument, an array. It will look through the array and only run the effect if one of those values has changed.

由于useEffect()每次在组件渲染时运行,因此我们可以使其仅在安装时运行一次。 效果挂钩可以使用第二个参数,即数组。 它将遍历数组,并且仅当这些值之一已更改时才运行效果。

componentDidMount:运行一次 (componentDidMount: Runs once)
// only run on mount. pass an empty array
useEffect(() => {
  // only runs once
}, []);
componentDidUpdate:在更改上运行 (componentDidUpdate: Runs on changes)
// only run if count changes
useEffect(
  () => {
    // run here if count changes
  },
  [count]
);

componentWillUnmount() (componentWillUnmount())

To run something before a component unmounts, we have to return a function from useEffect():

要在组件卸载之前运行某些东西,我们必须从useEffect()返回一个函数:

useEffect(() => {
  UsersAPI.subscribeToUserLikes();

  // unsubscribe
  return () => {
    UsersAPI.unsubscribeFromUserLikes();
  };
});

一起使用状态和效果 (Using State and Effects Together)

There’s no problem using them together. Together they can create functional components that work the same as your class components.

一起使用它们没有问题。 他们可以共同创建与类组件相同功能的组件。

Here’s a more real-world example of a component that fetches a list of users from GitHub API with useEffect() and keeps them using useState(). We’ll start by using useState() for users:

这是一个更真实的组件示例,该组件使用useEffect()从GitHub API获取用户列表, useEffect()用户使用useState() 。 我们将从为用户使用useState()开始:

使用状态 (Using State)
import React, { useState } from 'react';

function GitHubUsers() {
  const [users, setUsers] = useState([]);
}

We are setting users as an empty array to start in useState([]). Next, we will bring in the useEffect() hook and use fetch to grab data from the GitHub API:

我们将用户设置为一个空数组,以useState([]) 。 接下来,我们将引入useEffect()钩子,并使用fetch从GitHub API获取数据:

使用效果 (Using Effect)
import React, { useState } from 'react';

function GitHubUsers() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    fetch('https://api.github.com/users')
      .then(response => response.json())
      .then(data => {
        setUsers(data); // set users in state
      });
  }, []); // empty array because we only run once
}

Notice we are setting the second argument for useEffect as an empty array so it only runs once. Finally, we will show the list.

注意,我们将useEffect的第二个参数设置为一个空数组,因此它只能运行一次。 最后,我们将显示列表。

显示用户 (Displaying Users)
import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';

function GitHubUsers() {
  // ...other stuff here...

  return (
    
{users.map(user => (
{user.login}
))}
); }

We’ve also added Bulma CSS so it’s somewhat better looking than the default. That’s what the section and card classes are for:

React Hooks入门_第1张图片

我们还添加了Bulma CSS,因此比默认外观好一些。 这就是sectioncard类的用途:

结论 (Conclusion)

React State and Effect Hooks are wonderful additions to the library and will be tools to make it easier to learn React for new developers. A lot of Vue’s success is in its simplicity in creating components.

React State和Effect Hooks是库的绝佳补充,将成为使新开发人员更容易学习React的工具。 Vue的许多成功之处在于其创建组件的简便性。

Now with React, you don’t have to differentiate between a class or whether to use a functional component.

现在,借助React,您不必区分类还是是否使用功能组件。

翻译自: https://www.digitalocean.com/community/tutorials/getting-started-with-react-hooks

你可能感兴趣的:(react,vue,python,java,javascript,ViewUI)