【问题标题】:Access function argument inside function react hooks在函数反应钩子中访问函数参数
【发布时间】:2020-06-24 11:15:36
【问题描述】:

我正在编写一个用于从端点获取数据的自定义反应钩子。这就是函数的样子

import { useState } from "react";

const useHttp = async (endpoint, method, data) => {

    const [loading, setLoading] = useState(false)
    const [fetchedData, setfetchedData] = useState(null)

    setfetchedData(await fetch.method(endpoint));
    return [isLoading, fetchedData]
}

export default  useHttp;

如您所见,我想对传递给 useHttp 钩子的任何方法执行 fetch 请求。请有人指点我怎么做?

【问题讨论】:

  • 方法是给定 HTTP 方法的字符串吗?比如“get”、“post”、“put”等?

标签: reactjs react-redux react-hooks


【解决方案1】:

你不能将异步函数传递给 React Hooks。你必须useEffect

import { useState, useEffect } from "react";

const useHttp = (endpoint, method, options) => {
  const [isLoading, setLoading] = useState(false);
  const [fetchedData, setFetchedData] = useState(null);

  useEffect(() => {
    setLoading(true);

    fetch(endpoint, { method, ...options })
      .then(data => data.json())
      .then((json) => {
        // do something with JSON data
        setFetchedData(json);
      })
      .catch((err) => {
        // do something with err
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);
  return [isLoading, fetchedData];
};

export default useHttp;

【讨论】:

    【解决方案2】:

    使用useEffect钩子发出HTTP请求。

    fetch 函数接受一个可选的第二个参数,该参数是一个指定 HTTP 请求的各种选项的对象,其中一个选项是 method 选项。使用此method 选项指定请求方法。

    import { useState, useEffect } from "react";
    
    const useHttp = async (endpoint, method, data) => {
    
        const [loading, setLoading] = useState(false);
        const [fetchedData, setfetchedData] = useState(null);
    
        useEffect(() => {
            setLoading(true);
    
            fetch(endpoint, { method })
              .then(res => res.json())
              .then(data => {
                 setLoading(false);
                 setfetchedData(data);
              }) 
              .catch(err => {
                  setLoading(false);
                  console.log(err.message);
              });
    
        }, []);
    
    
        return [isLoading, fetchedData];
    }
    

    有关如何为fetch函数指定选项以及可以指定的不同选项的详细信息,请参阅using fetch

    如果你想使用async-await语法,你可以写useEffect钩子为:

    useEffect(() => {
    
        async function makeRequest() {
            setLoading(true);
    
            try {
                const response = await fetch(endpoint, { method });
                const data = await res.json();
                
                setLoading(false);
                setfetchedData(data);
            
            } catch (error) {
               setLoading(false);
               console.log(err.message);
            }
        }
    
        makeRequest();
    
    }, []);
    

    【讨论】:

      【解决方案3】:

      嗨,也许这对你有帮助:

      1-调用函数:

      const useHttp = async (url,method,data)=>{
                  var options = {
                      method:method,
                      headers: {
                          'Content-Type': 'application/json; charset=utf-8;'
                      }
                  };
                  if(method==='POST' && data)
                     options.body =  JSON.stringify(data);
                  const response = await fetch(url, options);
                  const rep = await response.json();
                  console.log(rep);
                  return rep;
      };
      

      在上面的代码中,首先创建您的请求选项,然后通过 fetch 将其发送到端点。

      2- 在组件中使用它,如下所示:

      setLoading(true);
      var rep = await useHttp(...)
      setLoading(false);
      

      【讨论】:

        猜你喜欢
        • 2020-01-12
        • 2020-12-30
        • 1970-01-01
        • 2020-08-22
        • 1970-01-01
        • 1970-01-01
        • 2020-08-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多