提交表单时如何执行自定义钩子?

时间:2021-04-13 09:58:32

标签: reactjs react-hooks

我正在学习 React 钩子,我构建了一个简单的钩子 useFetch,当我需要发出 GET 请求时它工作正常,但我如何将它用于 POST 请求提交表单时需要执行吗?据我所知,钩子只能在顶层执行

const useFetch = (url, options) => {

    const [ result, setResult ] = useState(null);
    const [ error, setError ] = useState(null);

    useEffect(() => {

        const fetchData = async () => {
            try {
                const response = await fetch(url, options);
                const res = await response.json();

                if ( response.ok) setResult(res);

            } catch (e: any) {
                 setError(e);
            }

        };
        fetchData();

    }, []);

    return [ result, error];
};

登录表单.jsx

function LoginForm() {

  const submitForm = async (e) => {
    e.preventDefault();
    // execute useFetch hook here
  }
}

0 个答案:

没有答案