简体   繁体   English

如何在函数中使用自定义钩子?

[英]How can i use custom hooks inside my function?

I tried to use my hook inside a function but it doesn't work, so now i tried to send a callback function to reset the hook params but it is still not working. 我试图在函数内使用钩子,但是它不起作用,所以现在我尝试发送一个回调函数来重置钩子参数,但是它仍然无法正常工作。

How can i make this custom hook work in my case? 如何在我的情况下使用此自定义挂钩?

const del = useFetch(null);
  const handleDelete = id => {
    del.setParams({
       hookUrl: "https://localhost:44354/api/car/" + id, 
       hookOptions: {}
    });

    console.log(del.response);
  };

The hook works fine for GETS cause i dont have any other behavior i want to do, but for the delete i need to pop a modal for example, i know i can use the fetch directly but just curious. 钩子对GETS的工作正常,因为我没有其他想要做的行为,但是对于删除,我需要弹出一个模态,例如,我知道我可以直接使用提取,但只是出于好奇。

import React from "react";

const useFetch = (url, options) => {
  debugger;
  const [params, setParams] = React.useState({
    hookUrl: url,
    hookOptions: options
  });
  const [response, setResponse] = React.useState(null);
  const [error, setError] = React.useState(null);
  React.useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(params.hookUrl, params.hookOptions);
        const json = await res.json();
        setResponse(json);
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, []);
  return { setParams, response, error };
};
export default useFetch;
  1. You cannot use a hook inside a function. 您不能在函数内部使用钩子。
  2. You are using the setParams (setState in a wrong way): 您正在使用setParams(以错误的方式使用setState):
const handleDelete = id => {
    del.setParams({
       hookUrl: "https://localhost:44354/api/car/" + id, 
       hookOptions: {}
    });
    console.log(del.response);
  };

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

相关问题 我不能在函数或效果钩子中使用自定义钩子的结果 - I cannot use the result of a custom hooks in a function or inside an effect hooks 如何在 useEffects 中使用带有自定义钩子的异步 function - how to use async function with custom hooks inside useEffects 如何从 function 内部访问我的反应钩子 state - How can I access my react hooks state from inside a function 无法在函数中使用我的 React 自定义挂钩给我错误 - Can't use my React custom hooks inside funcation give me ERROR 从 useEffect 内部的自定义钩子中使用集合 function - Use set function from custom hooks inside useEffect 我可以将 class 基础组件放入 function 基础组件中以使用反应挂钩吗? - Can I put class base components inside function base components to use react hooks? 如何修复 React 自定义挂钩中的“只能在 function 组件的主体内调用挂钩”错误? - How to fix 'Hooks can only be called inside the body of a function component' error in React custom hook? React - 不能在自定义钩子中使用钩子 - React - Can't use hooks in custom hooks 反应钩子 - 不能在普通异步 function 中使用钩子? - React hooks - Can't use hook inside plain async function? 如何在 react-query 的 useQueries 中使用自定义查询挂钩 - How to use custom query hooks inside useQueries in react-query
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM