【问题标题】:calling the Redux-Thunk Action after Component Mount by using useEffect. but got issue : React Hook useEffect has missing dependencies在组件挂载后使用 useEffect 调用 Redux-Thunk Action。但出现问题:React Hook useEffect 缺少依赖项
【发布时间】:2021-07-06 16:39:43
【问题描述】:

我需要在组件挂载后调用 API。但我正在使用功能组件。因此,我使用如下的 useEffect 钩子。

function ReportPage({ getAlertAuditLogs, getSensors, getUsers }) {
  
  ...
  
  useEffect(() => {
    getAlertAuditLogs()
    getSensors()
    getUsers()
  }, [])
  
  ...
  
}

但我收到了通知:

React Hook useEffect 缺少依赖项:“getAlertAuditLogs”、“getSensors”和“getUsers”。要么包含它们,要么删除依赖数组。如果“getAlertAuditLogs”更改过于频繁,请找到定义它的父组件并将该定义包装在 useCallback react-hooks/exhaustive-deps 中

这 3 个 api 没有任何参数。我该如何解决这个问题?

PS : getAlertAuditLogs 是 redux 操作,如下所示

import { reportConstants } from "../_constants"
import { alertAuditLogsService } from "../_services"

export const reportActions = {
  getAlertAuditLogs
}

function getAlertAuditLogs() {
  return (dispatch) => {
    dispatch(request())

    alertAuditLogsService.getAlertAuditLogs().then(
      (alertAuditLogs) => dispatch(success(alertAuditLogs.docs)),
      (error) => dispatch(failure(error.toString()))
    )
  }

  function request() {
    return { type: reportConstants.GET_ALERT_AUDIT_LOGS_ALL_REQUEST }
  }
  function success(alertAuditLogs) {
    return { type: reportConstants.GET_ALERT_AUDIT_LOGS_ALL_SUCCESS, alertAuditLogs }
  }
  function failure(error) {
    return { type: reportConstants.GET_ALERT_AUDIT_LOGS_ALL_FAILURE, error }
  }
}

【问题讨论】:

    标签: javascript reactjs react-redux redux-thunk


    【解决方案1】:

    编译器建议 - 函数的调用应该在 useEffect 参数中:

    为了提高效率(类似于缓存) - 只需将 useCallback() 包装到每 3 个函数中:

    这在将回调传递给优化的子组件时很有用 依赖于引用相等来防止不必要的渲染

    const getAlertAuditLogs = useCallback(
      () => {
        your function
      },
      [(here params from your functions - but you said there is paramteless)],
    );
    

    function ReportPage({ getAlertAuditLogs, getSensors, getUsers }) {
      
      ...
      
      useEffect(() => {
        getAlertAuditLogs()
        getSensors()
        getUsers()
      }, [getAlertAuditLogs, getSensors, getUsers ])
      
      ...
      
    }

    【讨论】:

    • 您好@piotr-Żak 感谢您的回答。我有件事要告诉你。 getAlertAuditLogs 是 redux-thunk 操作。在这种情况下,上述方法能解决我的问题吗?
    • @forevereffort - 尝试使用 - 来自钩子的 useDispatch - 它应该可以工作 - 如果你在函数内部调用 useCallback
    猜你喜欢
    • 2021-02-23
    • 1970-01-01
    • 2020-10-26
    • 2019-10-24
    • 2020-07-24
    • 2020-03-07
    • 2020-02-25
    • 2020-06-11
    • 2020-03-30
    相关资源
    最近更新 更多