首页 > 解决方案 > 不能将函数作为道具传递,总是有警告?

问题描述

这是我的代码:

const handleNotification = React.useCallback(
    type => {
      setSuccess(type);
      setTimeout(() => reset(), 1500);
    },
    [reset]
  );
  const sendRequest = React.useCallback(
    async () => {
      // don't send again while we are sending
      if (isSending) return;
      // update state
      setIsSending(true);
      // send the actual request
      try {
        await axios({
          method: "post",
          url: NONCOM_SEND_MAIL_URL,
          headers: {},
          data: {
            clientId,
            userId,
            email,
            subject: "Non-Compliant Certificate",
            templateCode: "REQNOTMET",
            entityId: entity_id
          }
        });
        handleNotification(true);
      } catch (e) {
        setError(e);
        handleNotification(false);
      }
      // once the request is sent, update state again
      if (isMounted.current)
        // only update if we are still mounted
        setIsSending(false);
    },
    [isSending, clientId, userId, email, entity_id, handleNotification]
  ); // update the callback if the state changes

我收到此警告:

'reset' 函数使 useCallback Hook(在第 35 行)的依赖关系在每次渲染时都发生变化。将其移动到 useCallback 回调中。或者,将“重置”定义包装到它自己的 useCallback() 挂钩中

如您所见,我已经将它包装在 useCallback 中?在这种情况下我做错了什么?reset 是此组件中的功能道具。为什么这不起作用?

标签: reactjsreact-hooks

解决方案


推荐阅读