React Hook 异步最佳实践 [英] React Hooks Async Best Practice

查看:41
本文介绍了React Hook 异步最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在使用 useEffects,可以将 componentDidMount 替换为带有钩子的 React 组件.

场景对服务器的初始唯一调用":

为了实现这一点,useEffect 中的 DependencyList(useEffect 的第二个参数)应该每次都是一个空数组,否则应用程序将向服务器发送每次状态更改的 fetch 调用.

这意味着,这是获取数据的最佳实践

useEffect(() => {console.log("useEffect, fetchData here");}, []);

使用 [] 作为 DependencyList 参数来禁用请求每个状态更改的服务器是最佳实践吗?

链接到githubhttps://github.com/facebook/react/issues/14326

解决方案

是的.这是最好的方法.

来自 react docs:><块引用>

传入一个空数组 [] 告诉 React 你的 effect 不依赖于来自组件的任何值,所以该 effect 只会在挂载时运行并在卸载时清理;它不会在更新时运行.

useEffect 是一个非常强大的,也是我最喜欢的钩子.您可以通过将一个或多个变量传递到第二个参数数组来监控一个或多个变量的状态变化,或者您可以使用您正在使用的方法监听挂载和卸载.

Now with use useEffects, there is a substitute for componentDidMount into a React Component with Hooks.

Scenario "initial unique call to a server":

To accomplish this, DependencyList (second argument of useEffect) in useEffect should every time an empty array otherwise the application will send every state change a fetch call to the server.

it means, this is the best practice to getData

useEffect(() => {
  console.log("useEffect, fetchData here");
}, []);

Is it best practice, to use [] as DependencyList param to disable server requesting every state changing?

Link to github https://github.com/facebook/react/issues/14326

解决方案

Yes. This is the best approach.

From the react docs:

Passing in an empty array [] of inputs tells React that your effect doesn’t depend on any values from the component, so that effect would run only on mount and clean up on unmount; it won’t run on updates.

useEffect is a very powerful, and my favorite, hook. You can monitor one or more variables for state changes by passing them into the second parameter array, or you can just listen for mounting and unmounting with the approach that you're using.

这篇关于React Hook 异步最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆