你应该避免的常见React Hooks错误

React Hook feature was first introduced on React 16.8 update and became immensely popular among developers due to its capabilities. It allows you to hook into React state and lifecycle features. And, sometimes, it could be challenging when using it for advanced use cases.

React Hook功能在React 16.8更新中首次引入,由于其功能,在开发者中大受欢迎。它允许你钩住React状态和生命周期功能。而且,有时候,当把它用于高级用例时,可能会有挑战。

In this article, I’ll discuss 5 common React Hooks mistakes every developer should avoid when building robust React applications.

在这篇文章中,我将讨论每个开发者在构建健壮的React应用程序时应该避免的5个常见的React Hooks错误。

Hooks should not be called within loops, conditions, or nested functions since conditionally executed Hooks can cause unexpected bugs.

钩子不应该在循环、条件或嵌套函数中被调用,因为有条件地执行钩子会导致意外的错误。

Avoiding such situations ensures that Hooks are called in the correct order each time the component renders. Also, it helps to keep the state of Hooks consistent across numerous useState and useEffect calls.

避免这种情况,可以确保每次组件渲染时Hooks的调用顺序是正确的。此外,它还有助于保持Hooks的状态在众多useStateuseEffect

In the below example, I’ve created a basic React component to choose a person from the dropdown and displays the selected person’s data.

在下面的例子中,我创建了一个基本的React组件,从下拉菜单中选择一个人,并显示所选人员的数据。

The SelectPerson component takes in the person’s id to be retrieved as a prop and keeps the personal data in the state variable person with the useEffect() Hook.

SelectPerson组件把要检索的人的id作为prop ,并把个人数据保存在状态变量person ,并有useEffect() Hook。

At a glance, everything looks fine, but you will get a console error since useState(), and useEffect() are not available in every render.

乍一看,一切都很好,但你会得到一个控制台错误,因为useState() ,和useEffect() ,并不是在每个渲染中都可用。

Screenshot by Author

作者的屏幕截图

To avoid this, you can simply move the return statement after the Hooks invocation.

为了避免这种情况,你可以简单地将返回语句移到Hooks调用之后。

So, always remember to use Hooks before any early returns at the top level of your React component.

所以,永远记得在你的React组件的顶层的任何早期返回之前使用Hooks。

In functional components, you can use useState Hook for state handling. Although it is pretty straightforward, there can be unex...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2025 iteam. Current version is 2.144.0. UTC+08:00, 2025-07-08 18:38
浙ICP备14020137号-1 $访客地图$