Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 实现useFetch react钩子在提交函数中工作_Reactjs_React Hooks - Fatal编程技术网

Reactjs 实现useFetch react钩子在提交函数中工作

Reactjs 实现useFetch react钩子在提交函数中工作,reactjs,react-hooks,Reactjs,React Hooks,我有很多经验,但我对hooks还是新手。 我在这个钩子之后修改了以下useFetch钩子: 从'react'导入{useState,useffect,useCallback} 导出默认函数useFetch(url、选项、{immediate}){ const[data,setData]=useState(null) const[error,setError]=useState(null) const[isPending,setIsPending]=useState(false) const ex

我有很多经验,但我对hooks还是新手。
我在这个钩子之后修改了以下
useFetch
钩子:

从'react'导入{useState,useffect,useCallback}
导出默认函数useFetch(url、选项、{immediate}){
const[data,setData]=useState(null)
const[error,setError]=useState(null)
const[isPending,setIsPending]=useState(false)
const executeFetch=useCallback(异步()=>{
设置显示(真)
setData(空)
设置错误(空)
等待获取(url、选项)
.then((response)=>response.json())
.然后((响应)=>setData(响应))
.catch((err)=>setError(err))
.最后(()=>setIsPending(false))
返回{data,error,isPending}
},[url、选项、数据、错误、isPending])
useffect(()=>{
如果(立即){
executeFetch()
}
},[executeFetch,立即])
返回{data,error,isPending,executeFetch}
}
我的问题是我想在submit函数中使用它,而钩子在其他函数中不起作用,就像这样(为了简洁起见,代码的简化版本):

导出默认函数SignupModal({closeModal}){
const{executeFetch}=useFetch(url,{options},
{立即:false}
)
异步函数handleSubmit(evt){
evt.preventDefault()
const{data,error,isPending}=wait executeFetch()
}
...
}
目前我有意在调用中抛出一个错误,但是错误变量仍然是
null

我错过了什么? 用钩子也可以吗


提前谢谢

React钩子只能在组件主体中使用,不能在其他函数中使用
executeFetch
本身正在返回
{data,error,isPending}
,这使得它成为一个嵌套的钩子,因此不能在handleSubmit中使用它

useFetch
已返回
{data,error,isPending,executeFetch}
因此executeFetch无需再次返回。您可以从useFetch钩子访问所有这些数据。在组件中调用executeFetch数据时,数据、错误和显示将由
setState
更新,这将导致钩子为更新的任何这些值返回一组新值

export default function useFetch(url, options, { immediate }) {
  const [data, setData] = useState(null)
  const [error, setError] = useState(null)
  const [isPending, setIsPending] = useState(false)

  const executeFetch = useCallback(async () => {
    setIsPending(true)
    setData(null)
    setError(null)
    await fetch(url, options)
      .then((response) => response.json())
      .then((response) => setData(response))
      .catch((err) => setError(err))
      .finally(() => setIsPending(false))
  }, [url, options, data, error, isPending])

  useEffect(() => {
    if (immediate) {
      executeFetch()
    }
  }, [executeFetch, immediate])
  return { data, error, isPending, executeFetch }
}


另一个建议是不要在钩子中立即传递布尔值来触发executeFetch,而是由调用方决定是否立即运行executeFetch

const { executeFetch, ... } = useFetch(....);
// you can call it immediately after setting the hook if you ever needed
await executeFetch()

我试过了,但是在
executeFetch
之后,我在
handleSubmit
中有代码,该代码需要访问
数据
错误
变量,但它们没有update@goldylucks根据您的评论更新了答案。感谢您花时间:)我的问题是在handle submit函数中,我无法访问useFetch钩子返回的内容。我在您的沙箱中添加了一个控制台日志数据。请注意,它只显示一次null。@goldylucks当您已经在handleSubmit中时,您无法访问useFetch钩子在主函数中返回的内容。第二次单击时,钩子中的数据不再为null,因为它保存以前的数据。您可以使用
.then()
访问handleSubmit中的数据或错误,或者您可以将两个回调
onSuccess
onError
传递给executeFetch,然后直接从executeFetch访问handleSubmit中的数据或错误,如
const useFetch = url => {
  const [error, setError] = useState(null);
  const [isPending, setIsPending] = useState(false);
  const [data, setData] = useState(null);

  const executeFetch = useCallback(
    // Here you will access to the latest updated options. 
    async ({ options }) => {
      setIsPending(true);
      setError(null);
        return await fetch(url, options)
        .then(response => response.json())
        .then(response => {
          setData(response); 
          return response;
        })
        .catch(err => {
          setError(err.message)
          return err;
        })
        .finally(() => setIsPending(false));
    },
    [url, setIsPending, setError]
  );
  return { data, error, isPending, executeFetch }
};
const { data, executeFetch, error, isPending } = useFetch("URL");
  
  const handleSubmit = useCallback(async (event) => {
    event.preventDefault();
    // I am passing hardcoded { id: 1 } as an argument. This can 
    // be a value from the state ~ user's input depending on your
    // application's logic.
    await executeFetch({ id: 1 }).then(response => {
      // Here you will access to 
      // data or error from promise. 
      console.log('RESPONSE: ', response);
    })
  }, [executeFetch]);
const { executeFetch, ... } = useFetch(....);
// you can call it immediately after setting the hook if you ever needed
await executeFetch()