gpt4 book ai didi

reactjs - `useEffect` 的预期返回是用来做什么的?

转载 作者:行者123 更新时间:2023-12-03 14:36:51 26 4
gpt4 key购买 nike

在 react documentation对于钩子(Hook),他们说:

"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]);

Demo app

请通过解释帮助我更好地理解这一点:
  • 为什么 return 是一个函数? return () => { ignore = true };
  • 在这个例子中忽略了什么?

  • 谢谢!

    最佳答案

    为什么 return 是一个函数? return () => { ignore = true };
    来自 docs ,

    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!



    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函数执行它检查 ignoretrue并相应地设置 setProduct(json) .这意味着我们有 state调用 product并在 state 中设置值使用 setProduct(json) .这个 product in 状态用于在页面上呈现详细信息。
    注:[productId]作为第二个参数传递给 useEffect , fetchProduct函数只会在 productId 时执行变化。
    optimizing performance by skipping effects .

    关于reactjs - `useEffect` 的预期返回是用来做什么的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56800694/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com