React Hooks入门

React Hooks are a great new feature in React 16.8. React 16.6 brought some awesome new things like React.memo() and React.lazy and Suspense. The React team isn't stopping there.

React Hooks是React 16.8中的一个很棒的新功能。 React 16.6带来了一些很棒的新功能,例如React.memo()以及React.lazy和Suspense。 React团队不止于此。

Hooks are a feature that you'll end up using every single day of your React development. React Hooks are now out in React 16.8! Hooks are great because we get more tools as React developers.

挂钩是您将在React开发的每一天中最终使用的功能。 React Hooks现在已经在React 16.8中发布了 ! 钩子很棒,因为我们作为React开发人员拥有更多的工具。

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.Component和类。 钩子让我们在功能组件中使用这些功能!

什么是挂钩? ( What are Hooks? )

React Hooks are a way to add React.Component features to functional components. Features like:

React Hooks是一种向功能组件添加React.Component功能的方法。 功能如下:

  • State

  • Lifecycle

    生命周期

Hooks let you use React's features without classes.

钩子让您无需类即可使用React的功能。

Don't worry though, classes aren't being removed or discouraged. We're being given more ways to code!

不过请不要担心, 不会删除或阻止类 。 我们将获得更多的编码方式!

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 (
      <div>
        <h1>{this.state.count}</h1>

        <button onClick={this.setCount}>Count Up To The Moon</button>
      </div>
    );
  }
}

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 (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>Count Up To The Moon</button>
    </div>
  );
}

Here's a CodeSandbox for the above example:

这是上述示例的CodeSandbox:

Notice how much easier the functional component would be for beginners just learning React.

注意,对于初学者来说,学习React会使功能组件变得容易得多。

useState()的语法是什么? ( What is this 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 vs array destructuring to see why the array way is helpful. Object destructuring requires more writing to grab a variable and rename it.

让我们比较对象分解与数组分解,以了解为什么数组方式很有用。 对象解构需要更多的编写来获取变量并将其重命名。

对象分解 (Object Destructuring)
// object destructuring. lots of writing!
const users = { admin : 'chris' , user : 'nick' } ;

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

That bottom line can be a bit difficult to read. 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()给我们什么? ( What does useState() give us? )

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开始。

班怎么了? ( What's wrong with classes? )

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.

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

There are no plans to remove classes support. We just have another way to code

没有计划删除类支持。 我们还有另一种编码方式

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 < div > { /_ use all those things here _/ } < / div > ;
}

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.

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

Effects are similar to componentDidMount, componentDidUpdate, and componentWillUnmount

效果类似于componentDidMount,componentDidUpdate和componentWillUnmount

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 < div > stuff goes here < / div > ;
  }
}

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 < div > stuff goes here < / div > ;
}

And the CodeSandbox for this example:

以及本示例的CodeSandbox:

useEffect() is... effectively ?... similar to componentDidMount and componentDidUpdate

useEffect()是...有效吗?...类似于componentDidMountcomponentDidUpdate

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

Since useEffect() runs every time a component renders, how do we 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()呢 ( What about componentWillUnmount() )

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

要在组件卸载之前运行某些东西,我们只需要从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获取用户列表,并使用useState()保持用户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 (
    <div className="section">
      {users.map(user => (
        <div key={user.id} className="card">
          <h5>{user.login}</h5>
        </div>
      ))}
    </div>
  );
}

Not the prettiest but it gets the job done! I've also added Bulma so it's somewhat better looking than default. That's what the section and card classes are for:

不是最漂亮,但可以完成工作! 我还添加了布尔玛(Bulma),因此看起来比默认更好。 这就是sectioncard类的用途:

Here's the CodeSandbox:

这是CodeSandbox:

结论 ( 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. It's just an object.

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

Now with React, you don't have to differentiate between "is it a class?" or "should I use a functional component?"

现在有了React,您不必区分“这是一类吗?” 或“我应该使用功能组件吗?”

翻译自: https://scotch.io/tutorials/getting-started-with-react-hooks

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值