`useEffect` 的预期回报用于什么? [英] What is the expected return of `useEffect` used for?

查看:29
本文介绍了`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. 为什么返回是一个函数?<代码>返回() =>{ 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 Hook ignore 中设置为,let ignore = false;.当 fetchProduct 函数执行时,它会检查 ignore 是否为 true 并相应地设置 setProduct(json).这意味着我们将 state 称为 product 并使用 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] 作为第二个参数传递给 useEffectfetchProduct 函数只会得到当 productId 改变时执行.

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

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

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

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