"useEffect"的预期收益是什么? [英] What is the expected return of `useEffect` used for?

查看:44
本文介绍了"useEffect"的预期收益是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在React 文档表示他们说的钩子:

In the React documentation for hooks they say:

"这还允许您处理本地的乱序响应效果内部的变量"

"This also allows you to handle out-of-order responses with a local variable inside the effect"

useEffect(() => {
    let ignore = false;
    async function fetchProduct() {
      const response = await fetch('http://myapi/product/' + productId);
      const json = await response.json();
      if (!ignore) setProduct(json);
    }

    fetchProduct();
    return () => { ignore = true };
  }, [productId]);

演示应用

请通过解释帮助我更好地理解这一点:

Please help me understand this better by explaining:

  1. 为什么返回一个函数? return()=>{ignore = true};
  2. 在此示例中忽略了什么?

谢谢!

推荐答案

为什么返回函数?return()=> {ignore = true};

文档

我们为什么要从效果中返回一个函数?这是可选的效果清除机制.每个效应可能返回清理它的功能.这使我们可以保持彼此之间添加和删除订阅的逻辑.它们具有相同的作用!

Why did we return a function from our effect? This is the optional cleanup mechanism for effects. Every effect may return a function that cleans up after it. This lets us keep the logic for adding and removing subscriptions close to each other. They’re part of the same effect!

还有

React何时确切地清除效果?当组件卸载时,React进行清除.但是,正如我们之前所了解的,效果会在每个渲染中运行,而不仅仅是一次.这就是为什么React在下一次运行效果之前还要清除先前渲染中的效果的原因.我们将在下文中讨论为什么这有助于避免错误以及如何选择退出此行为,以防它在以后造成性能问题.

When exactly does React clean up an effect? React performs the cleanup when the component unmounts. However, as we learned earlier, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time. We’ll discuss why this helps avoid bugs and how to opt out of this behavior in case it creates performance issues later below.

在此示例中忽略了什么?

最初在 useEffect 中设置了挂钩 ignore ,就像 let ignore = false; 一样.当 fetchProduct 函数执行时,它会检查 ignore 是否为 true ,并相应地设置 setProduct(json).这意味着我们有一个名为 product state ,并使用 setProduct(json)将值设置为 state .此 product 状态用于呈现页面上的详细信息.

Initially in useEffect Hook ignore is set like, let ignore = false;. When fetchProduct function executes it checks for ignore is true and accordingly sets setProduct(json). This means we have state called product and setting the value in state using setProduct(json). This product in state is used to render details on page.

注意:由于将 [productId] 作为第二个参数传递给 useEffect ,因此 fetchProduct 函数将仅获得当 productId 更改时执行.

Note: As [productId] is passed as second argument to useEffect, fetchProduct function will only get executes when productId changes.

请参见通过跳过效果来优化性能.

这篇关于"useEffect"的预期收益是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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