reactjs - React Hook useEffect 依赖问题

标签 reactjs react-hooks react-context use-effect

我的应用程序上收到一条警告消息,我尝试了很多方法来删除它,但没有成功。错误消息:

React Hook useEffect has a missing dependency: 'updateUserData'. Either include it or remove the dependency array react-hooks/exhaustive-deps

我不想通过评论排除它以避免出现问题,但我想以“最佳实践”方式修复它。

我想调用该更新程序函数并更新我的组件,以便我可以在其他组件中共享该上下文。

那么...我做错了什么? (非常欢迎对其余部分进行任何代码审查!)

感谢一百万!

如果我添加 [] 作为 useEffect 的第二个参数,我会收到警告,删除它我会得到一个无限循环。

同时添加 [updateuserData] 会导致无限循环。

import React, { useState } from "react";
import UserContext from "./UserContext";


interface iProps {
    children: React.ReactNode
}

const UserProvider: React.FC<iProps> = (props) => {
    // practice details
    const [userState, setUserState] = useState({
        id'',
        name: ''
    });

    // practice skills
    const [userProfileState, setuserProfileState] = useState([]);

    // user selection
    const [userQuestionsState, setuserQuestionsState] = useState({});


    return (
        <UserContext.Provider value={{
            data: {
                user: userState,
                userProfile: userProfileState,
                questions: userQuestionsState
            },
            updateuserData: (id : string) => {
                 // call 3 services with axios in parallel
                 // update state of the 3 hooks
            }
        }}
        >
            {props.children}
        </UserContext.Provider>
    );
};

export default UserProvider;
const UserPage: React.FC<ComponentProps> = (props) => {


    const {data : {user, profile, questions}, updateUserData}: any = useContext(UserContext);

    useEffect(() => {
        // update information
        updateUserData("abcId")
    }, []);



    return <div>...</div>

}

想法如下:

  • 我有一个上下文

  • 我为该内容创建了提供程序

  • 该上下文公开数据和更新器函数

  • 我在带有 useEffect Hook 的组件中使用该提供程序,并收到警告

  • 我希望将有关获取和更新上下文的所有逻辑保留在提供程序内,因此我不会将其复制到需要它的其他组件上。

最佳答案

首先,无限循环是由于上下文正在更新而导致组件重新渲染,上下文更新导致组件重新渲染。添加依赖项应该可以防止此循环,但在您的情况下,情况并非如此,因为当您的上下文更新时,会提供一个全新的 updateuserData ,因此引用相等性检查会检测到更改并在以下情况下触发更新:你不希望这样。

一种解决方案是更改在 UserProvider 中创建 updateUserState 的方式,例如使用useCallback 传递相同的函数,除非依赖项之一发生更改:

const UserProvider: React.FC<iProps> = (props) => {
  // practice details
  const [userState, setUserState] = useState({
      id'',
      name: ''
  });

  // practice skills
  const [userProfileState, setuserProfileState] = useState([]);

  // user selection
  const [userQuestionsState, setuserQuestionsState] = useState({});
  const updateuserData = useCallback(id=>{
    // call your services
  }, [userState, userProfileState, userQuestionsState])

  return (
      <UserContext.Provider value={{
          data: {
              user: userState,
              userProfile: userProfileState,
              questions: userQuestionsState
          },
          updateuserData
      }}
      >
          {props.children}
      </UserContext.Provider>
  );
};

关于reactjs - React Hook useEffect 依赖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58167449/

相关文章:

javascript - React : Map rendering component causing unnecessary re-renders, 子键 Prop 不起作用?

javascript - react : App requests same endpoint multiple times

reactjs - 在reactJS中每X秒发出一次API请求

javascript - React useContext 返回未定义

javascript - React 上下文 - 'contextType' 未定义

reactjs - 使用 jest 和 react-testing-library 测试 react 上下文

javascript - 与react-router-dom 4 react - 无法读取未定义的属性 'params'

reactjs - 如何更新状态数组中的对象属性

javascript - 在父组件内添加一个具有 N 次的子组件(基于状态值)

javascript - 将Apollo-link-error中的Apollo React onError添加到链接const