简体   繁体   English

useEffect 调用了两次 - useCallback 没有效果

[英]useEffect called twice - useCallback has not effect

An API call is being made from useEffect() and when the application is refreshed, useEffect() is called twice and API is call is made twice.正在从 useEffect() 进行 API 调用,当应用程序刷新时,useEffect() 被调用两次,API 被调用两次。

// App.js // 应用程序.js

import { useEffect, useCallback } from "react";

function App() {
  const fetchUsers = useCallback(async () => {
    try {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const data = await response.json();
      console.log("data: ", data); // displayed two times in console.
    } catch (error) {
      console.log("Error in catch!");
    }
  }, []);

  useEffect(() => {
    fetchUsers();
  }, [fetchUsers]);
}

export default App;

how to fix this?如何解决这个问题? useCallback() also has no effect in not invoking fetchUsers() function twice. useCallback() 对于不调用 fetchUsers() function 两次也没有影响。

Here is the full code.这是完整的代码。 CodeSandBox代码沙盒

using react v18使用反应 v18

Edit: Removing <React.StrictMode> has solved the issue, but I don't want to remove it, as it is useful in warning potential issues in the application.编辑:删除 <React.StrictMode> 已经解决了这个问题,但我不想删除它,因为它对于警告应用程序中的潜在问题很有用。

Is there any other solution?还有其他解决办法吗?

New Strict Mode Behaviors 新的严格模式行为

In short, there is no "fix" as this is intentional.简而言之,没有“修复”,因为这是故意的。 Do not remove Strict mode as some users are suggesting.不要像某些用户建议的那样删除Strict模式。 You will see it only in development mode.您只会在开发模式下看到它。

In the future, we'd like to add a feature that allows React to add and remove sections of the UI while preserving state.将来,我们希望添加一个功能,允许 React 在保留状态的同时添加和删除 UI 部分。 For example, when a user tabs away from a screen and back, React should be able to immediately show the previous screen.例如,当用户从一个屏幕上移开并返回时,React 应该能够立即显示上一个屏幕。 To do this, React would unmount and remount trees using the same component state as before.为此,React 将使用与以前相同的组件状态卸载和重新安装树。

This feature will give React apps better performance out-of-the-box, but requires components to be resilient to effects being mounted and destroyed multiple times.此功能将为 React 应用程序提供更好的开箱即用性能,但要求组件能够对多次安装和销毁的效果具有弹性。 Most effects will work without any changes, but some effects assume they are only mounted or destroyed once.大多数效果无需任何更改即可工作,但有些效果假定它们只安装或销毁一次。

To help surface these issues, React 18 introduces a new development-only check to Strict Mode.为了帮助解决这些问题, React 18 为严格模式引入了一个新的仅限开发的检查。 This new check will automatically unmount and remount every component, whenever a component mounts for the first time, restoring the previous state on the second mount .每当第一次挂载组件时,此新检查将自动卸载并重新挂载每个组件,并在第二次挂载时恢复先前的状态

It's the Default behavior in react18.You can check using the below link.这是 react18 中的默认行为。您可以使用以下链接进行检查。

techiediaries.com/react-18-useeffect techiediaries.com/react-18-useeffect

You can try this solution:你可以试试这个解决方案:

Removed strict mode of react and it works normally.去掉了严格的反应模式,它可以正常工作。

import { useEffect, useCallback } from "react";

function App() {
  const fetchUsers = useCallback(async () => {
    try {
      const response = await fetch(
        "https://jsonplaceholder.typicode.com/users"
      );
      const data = await response.json();
      console.log("data: ", data);
    } catch (error) {
      console.log("Error in catch!");
    }
  }, []);

  useEffect(() => {
    var ignore = false;
    if (!ignore) {
      ignore = true;
      fetchUsers();
    }
  }, [fetchUsers]);
}

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM