react hooks_如何破坏React Hooks的基础

 2023-09-06 阅读 24 评论 0

摘要:react hooksHooks have become a pretty powerful new feature of React. They can be intimidating if you’re not really sure what’s going on behind the scenes. The beauty is now being able to manage state in a simple (and reusable) manner within function com

react hooks

Hooks have become a pretty powerful new feature of React. They can be intimidating if you’re not really sure what’s going on behind the scenes. The beauty is now being able to manage state in a simple (and reusable) manner within function components.

挂钩已经成为React的强大功能。 如果您不确定幕后发生的事情,他们可能会吓到您。 美人现在能够以简单(可重用)的方式在功能组件内管理状态。

But why not use a class? Without getting too far away from the topic, functions provide a more straightforward way to write your components, guiding you to write in a cleaner and more reusable way. Bonus: it typically makes writing tests easier.

但是为什么不使用一个类呢? 在不离主题太远的情况下,函数提供了一种更直接的方式来编写组件,从而指导您以一种更简洁,更可重用的方式进行编写。 奖励:通常可以简化编写测试的过程。

There’s a lot of use cases for hooks, so I won’t dive into examples. It shouldn’t be too bad to get up to speed with a few quick lines. For the sake of this article, let’s assume browser cookies aren’t a thing and these are the edible type.

钩子有很多用例 ,因此我不会深入研究示例。 几行快速入门就不算太糟。 为了本文的方便,让我们假设浏览器cookie不是什么,而是可食用的。

Here we have MyCookies, a function component, which we can consider our cookie jar. Let's say we want to internally keep track of how many cookies we have in the jar. With the new hooks API, we can add a simple line using useState to handle the job.

在这里,我们有MyCookies ,一个功能组件,我们可以考虑使用它的cookie罐。 假设我们要在内部跟踪罐子中有多少个Cookie。 使用新的hooks API,我们可以使用useState添加一条简单的行来处理作业。

const MyCookies = () => {const [ cookies, setCookieCount ] = useState(0);...
};

等等,我们如何从中获取Cookie? (Wait, how do we get cookies out of that?)

If you think the above is magic and are wondering how the values in the array are getting set, you’ll need to understand the basics of array destructuring.

如果您认为以上内容是魔术,并且想知道如何设置数组中的值,则需要了解数组解构的基础知识。

While destructuring an object will use the same key wherever you try to pull it from, arrays destructure using the order of the items within the array.

销毁对象时,无论您尝试从何处提取对象,都将使用相同的键,而数组则使用数组中各项的顺序进行销毁。

const [ one, two ] = [ 1, 2 ];
console.log(one); // 1
console.log(two); // 2

While the above seems like it’s naming them in a particular order, it’s not as shown below:

上面的代码似乎是按特定的顺序命名的,但它没有如下所示:

const [ two, one ] = [ 1, 2 ];
console.log(two); // 1
console.log(one); // 2

Without going too far down the technical rabbit hole, useState is a function that returns an array that we're destructuring for use within our component.

useState是一个函数,它返回一个我们正在useState的数组以供在组件中使用, useState无需太useState

What about the 0 inside the invocation of useState itself? That’s simply the initial value we’re setting the state instance to. In this case, we’ll sadly start off with 0 cookies.

调用useState本身内部的0怎么样? 这只是我们将状态实例设置为的初始值。 在这种情况下,我们将以0个cookie开始。

其实使用状态 (Actually, use state)

Once we have our destructured cookies and the setCookiesCount function, we can start interacting with the component's local state like you might do using setState within a class component.

一旦有了解构的cookiessetCookiesCount函数,就可以开始与组件的本地状态进行交互,就像在类组件中使用setState一样。

At render time, our cookies value will be that invocation of useState's internal state value, similar to what you might see with this.state. To update that value, we can simply call setCookiesCount.

在渲染时,我们的cookies值将是useState的内部状态值的调用,类似于您在this.state看到的this.state 。 要更新该值,我们可以简单地调用setCookiesCount

const MyCookies = () => {const [ cookies, setCookieCount ] = useState(0);return (<><h2>Cookies: { cookies }</h2><button onClick={() => setCookieCount(cookies + 1)} >Add Cookie</button></>);
};

If you’re more used to the class syntax, you might update state using this.setState looking something like this:

如果您更习惯使用类语法,则可以使用this.setState更新状态,如下所示:

const MyCookies = () => {const [ cookies, setCookieCount ] = useState(0);useEffect(() => {getCookieCount().then((count) => {setCookieCount(count);})});...
};

如何使用效果 (How to use effects)

Often components need a way to create side effects that won’t necessarily interrupt the functional flow of a function component. Say we have the number of cookies we have saved on a server somewhere, we might want to fetch that count when the app loads.

通常,组件需要一种产生副作用的方法,这些副作用不一定会中断功能组件的功能流程。 假设我们拥有保存在某处服务器上的Cookie数量,那么我们可能希望在应用加载时获取该计数。

const MyCookies = () => {const [ cookies, setCookieCount ] = useState(0);useEffect(() => {getCookieCount().then((count) => {setCookieCount(count);})}, []);...
};

After the component renders, everything inside of useEffect will run. Any side effects originating from useEffect will only occur after the render is complete. That said, once useEffect does run, we fire getCookieCount and use our previous setCookieCount function to update the state of the component.

组件渲染后, useEffect内的所有内容都将运行。 源自useEffect任何副作用都只会在渲染完成之后发生。 就是说,一旦useEffect确实运行,我们将触发getCookieCount并使用我们之前的setCookieCount函数来更新组件的状态。

等等,有什么问题… (Hold up, there’s something wrong…)

There’s a gotcha in the code above though. That effect will run every time, essentially wiping out any new increments to our cookie value from our original Add Cookie button.

上面的代码中有一个陷阱。 该效果每次都会运行,实际上是从我们原来的“添加Cookie”按钮中删除了cookie值的任何新增量。

To get around this, we can set a 2nd argument to the useEffect function that allows us to let React know when to run it again. In our example above, setting that 2nd argument to an empty array will make it run only once.

为了解决这个问题,我们可以为useEffect函数设置第二个参数,该参数允许我们让React知道何时再次运行它。 在上面的示例中,将第二个参数设置为空数组将使其仅运行一次。

const MyCookies = ({cookieType = 'chocolate'}) => {const [ cookies, setCookieCount ] = useState(0);useEffect(() => {getCookieCount().then((count) => {setCookieCount(count);})}, [ cookieType ]);...
};

In most cases though, you’ll want to pass an array of dependencies that, when changed, will cause useEffect to fire again. Say, for example, you're fetching the count of a specific cookie type and want to get the count again if that type changes.

不过,在大多数情况下,您需要传递一组依赖项,这些依赖项在更改时将导致useEffect再次触发。 举例来说,假设您要获取特定Cookie类型的计数,并希望在该类型发生更改时再次获得该计数。

import BasketContext from 'context';const Basket = ({children}) => {return (<BasketContext.Provider value={basketItems}><h1>My Basket</h1>{ children }</BasketContext.Provider>);
}// MyCookies.js
const MyCookies = ({cookieType = 'chocolate'}) => {const basketItems = useContext(BasketContext);...
};

In the above code, any time our prop cookieType changes, React knows that we depend on it for our effect, and will rerun that effect.

在上面的代码中, cookieType我们的prop cookieType发生更改,React就会知道我们依赖它来实现效果,并将重新运行该效果。

尝试利用上下文 (Trying to make use of context)

I’m not going to go into the details of React’s context API as that’s a little out of scope. However, if you’re familiar with it, the useContext hook lets you easily make use of your context from within your function component.In the above code, given our already created context, we can immediately “use” said context and collect the values passed into our context provider.

我将不涉及React的上下文API的细节,因为这有点超出范围。 但是,如果您熟悉它,可以使用useContext挂钩轻松地从函数组件中使用上下文。在上面的代码中,给定已经创建的上下文,我们可以立即“使用”所述上下文并收集值传递给我们的上下文提供程序。

import BasketContext from 'context';const Basket = ({children}) => {return (<BasketContext.Provider value={basketItems}><h1>My Basket</h1>{ children }</BasketContext.Provider>);
}// MyCookies.js
const MyCookies = ({cookieType = 'chocolate'}) => {const basketItems = useContext(BasketContext);...
};

清洁钩子 (Cleaning your hooks)

What makes hooks even more powerful is combining and abstracting them DRYing up your code in a cleaner way. As a quick last example, we can take our cookie examples of useState and useEffect and abstract them into their own use[Name] function, effectively creating a custom hook.

使钩子更加强大的是将它们组合和抽象化以更简洁的方式处理代码。 作为最后一个快速示例,我们可以使用useStateuseEffect cookie示例, useState它们抽象到自己的use[Name]函数中,从而有效地创建自定义钩子 。

// useCookies.js
function useCookies(initialCookieCount) {const [ cookies, setCookieCount ] = useState(initialCookieCount);useEffect(() => {getCookieCount().then((count) => {setCookieCount(count);})}, []);function addCookie() {setCookieCount(cookies + 1);console.log('?');}function removeCookie() {setCookieCount(cookies - 1);console.log('?');}return {cookies,addCookie,removeCookie}
};// MyCookies.js
const MyCookies = () => {const { cookies, addCookie, removeCookie } = useCookies(0);...
};

We were safely able to abstract our state logic and still utilize it to manage our cookies.

我们可以安全地抽象出状态逻辑,并仍然利用它来管理cookie。

还有更多吸引 (Plenty more to get hooked on)

These are the basic 3 hooks React gives us, but there are many more they provide out of the box, all with the same underlying principles that the React documentation does a good job at explaining.

这些是React提供给我们的3个基本钩子,但是它们提供了更多的现成功能 ,所有这些钩子都具有相同的基本原理,这些基本原理使React文档可以很好地解释。

Follow me for more Javascript, UX, and other interesting things!

  • 🐦 Follow Me On Twitter

    Twitter在Twitter上关注我

  • 📽️ Subscribe To My Youtube

    Subscribe️订阅我的YouTube

  • ✉️ Sign Up For My Newsletter

    ✉️注册我的时事通讯

Originally published at https://www.colbyfayock.com/2019/04/destructuring-the-fundamentals-of-react-hooks.

最初发布于https://www.colbyfayock.com/2019/04/destructuring-the-fundamentals-of-react-hooks 。

翻译自: https://www.freecodecamp.org/news/how-to-destructure-the-fundamentals-of-react-hooks-d13ff6ea6871/

react hooks

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/7309.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息