react钩子
Anyone who has written a class component in a large project knows that component life-cycle methods can get bloated. Code in componentDidMount and componentWillUnmount gets tangled amongst other blocks of unrelated code. Hooks provide a way to write modular and stateful components that is easy to test and reuse.
在大型项目中编写类组件的任何人都知道,组件生命周期方法会变得肿。 componentDidMount和componentWillUnmount代码在其他无关代码块中纠结在一起。 挂钩提供了一种编写模块化的有状态组件的方法,该方法易于测试和重用。
The learning curve for hooks is steep. To help with the transition, I’ll be focusing on useState and useEffect. As a consequence, the performance of your application won’t be ideal. However, wrapping your mind around hooks becomes a much simpler feat. In future posts, I’ll discuss the more advanced hooks and how they help with performance.
钩子的学习曲线很陡。 为了帮助进行过渡,我将重点介绍useState和useEffect 。 结果,您的应用程序的性能将不是理想的。 但是,将您的想法挂在钩子上将变得更加简单。 在以后的文章中,我将讨论更高级的钩子及其对性能的帮助。
A couple of quick notes
几个快速笔记
Hooks can only exist inside functional components or inside other hooks.挂钩只能存在于功能组件内部或其他挂钩中。Functional components do not have life cycle events like class components. This is intentional. useEffect can be used to simulate a few life cycle events. We will explore this in a later post.
功能组件没有类组件之类的生命周期事件。 这是故意的。 useEffect可用于模拟一些生命周期事件。 我们将在以后的文章中对此进行探讨。
Let’s get started.
让我们开始吧。
The most basic hook is useState. It takes an initialization value and returns a reference to the current value as well as a function to update that value. Let's create a state that keeps track of a counter;
最基本的钩子是useState 。 它采用一个初始化值,并返回对当前值的引用以及一个用于更新该值的函数。 让我们创建一个跟踪计数器的状态;
const [ count, setCount ] = useState(0);You can provide an initialization function instead of a starting value if you wish;
如果需要,可以提供一个初始化函数而不是一个起始值。
const [ count, setCount ] = useState(() => { const startingCount = 0; ... // some logic return startingCount;);When a functional component is re-rendered it does not re-initialize. Instead, React returns the cached value and update function. So all future renders after the first ignores initialization.
重新渲染功能组件时,不会重新初始化。 相反,React返回缓存的值和更新函数。 因此,第一个之后的所有将来渲染都将忽略初始化。
You can have as many useState s’ as you want to keep track of any number of values.
您可以使用useState多个useState来跟踪任意数量的值。
const [ count, setCount ] = useState(0);const [ anotherCount, setAnotherCount ] = useState(10);const [ message, setMessage ] = useState("Default message");const [ expanded, setExpanded ] = useState(false);Let’s make a simple counter that displays a value along with two buttons; A button that adds one to the value and a button to subtract one. The function we’ll pass to the add button’s onClick will look like:
让我们做一个简单的计数器,它同时显示一个值和两个按钮。 一个将值加一的按钮和一个减一的按钮。 我们将传递给添加按钮的onClick的函数如下所示:
const onPlus = () => { setCount(count + 1);};The minus button’s onClick:
减号按钮的onClick :
const onMinus = () => { setCount(count - 1);};Put it all together:
放在一起:
function Counter() { const [count, setCount] = useState(0); const onPlus = () => { setCount(count + 1); }; const onMinus = () => { setCount(count - 1); }; return ( <div> <button onClick={onPlus}>Plus</button> <button onClick={onMinus}>Minus</button> <div>{count}</div> </div> );}Here is a sandbox with a slight alteration of initializing on with a passed-in property to demonstrate that re-renders do not re-run initialization.
这是一个沙盒,其中带有传入属性的初始化略有更改,以演示重新渲染不会重新运行初始化。
演示地址
This hook allows you to perform side effects inside of functional components. It takes a function followed by an optional dependency array. The side effect only re-runs if one or more dependencies change.
该挂钩可让您在功能组件内部执行副作用。 它需要一个函数,后跟一个可选的依赖项数组。 仅当一个或多个依赖项更改时,副作用才会重新运行。
useEffect(someFunction, dependencyArray);Let’s take our previous ‘counter’ example and modify it so it changes the color of the count label to the following;
让我们以前面的“计数器”示例为例,并对其进行修改,以便将计数标签的颜色更改为以下颜色;
Red; if the count is negative. 红; 如果计数为负。 Black; if the count is 0. 黑色; 如果计数为0。 Green; if the count is positive. 绿色; 如果计数为正。Create a new useState that will store the current label color. We’ll use hex values in this example. To re-run our side-effect that updates our state color, we need to put count in the dependency array.
创建一个新的useState ,它将存储当前标签的颜色。 在此示例中,我们将使用十六进制值。 要重新运行更新状态颜色的副作用,我们需要将count放入依赖项数组中。
const [count, setCount] = useState(startingCount);const [countLabelColor, setCountLabelColor] = useState("#000000");useEffect(() => { if (count < 0) { setCountLabelColor("#ff0000"); // red } else if (count === 0) { setCountLabelColor("#000000"); // black } else { setCountLabelColor("#00ff00"); // green }}, [count]);Here is a sandbox with a working example;
这是一个带有工作示例的沙盒;
演示地址
That’s it! With useState and useEffect you are well on your way to learning hooks. Most things you would want to accomplish can be done with these two hooks. There are concerns about performance if you only stick to these two hooks. For example; the useEffect sandbox above is rendering more than once every time a button gets clicked. This isn’t an issue at this scale but as components get more complex and applications get larger, the consequences become clearer. For now, master these two hooks before moving on to the more advanced ones.
而已! 使用useState和useEffect可以很好地学习钩子。 您想要完成的大多数事情都可以通过这两个钩子完成。 如果仅坚持使用这两个挂钩,则可能会对性能造成影响。 例如; 每次单击按钮时,上面的useEffect沙箱都会渲染多次。 在这个规模上,这不是问题,但是随着组件变得越来越复杂,应用程序越来越大,后果变得更加明显。 现在,先掌握这两个钩子,然后再继续使用更高级的钩子。
As with anything, keep practicing, and good luck!
像其他任何事情一样,继续练习,祝您好运!
翻译自: https://medium.com/swlh/get-acquainted-with-react-hooks-in-15-minutes-a64bb6d807c7
react钩子