NodeJS 我收到类型错误:使用此函数时无法获取

hxzsmxv2  于 2023-02-18  发布在  Node.js
关注(0)|答案(2)|浏览(126)

我试图用mern制作一个完整的堆栈传输管理系统,但它运行正常15秒,之后出现TypeError:无法获取进来,它在我的控制台中呈指数增长。

useEffect(() => {
 const fetchBus = async () => {
 try{
 const response = await fetch("/api/buses");
 const json = await response.json();
 
 if (response.ok) {
 dispatch({ type: "SET_BUS", payload: json });
 }
 
 }
 catch(error){
 console.log(error)
 }
 };
 fetchBus(); 
 }, [handleOwnership,handleAvailable]);
z9smfwbn

z9smfwbn1#

由于fetch()response.json()都是异步任务,都返回一个Promise,需要在一个**if(response.ok){}**块中解析json数据:

替换:

useEffect(() => {

 const fetchBus = async () => {

 try{

   const response = await fetch("/api/buses");
   //const json = await response.json();//Not here
   
   if (response.ok) {
    const json = await response.json();//But Here
    dispatch({ type: "SET_BUS", payload: json });
   }
 
 }
 catch(error){
   console.log(error)
  }
 };

 fetchBus(); 
 }, [handleOwnership,handleAvailable]);

获取JSON GET请求:

let url = 'https://someurl.com';

let response = await fetch(url);
let responseOK = response && response.ok;
if (responseOK) {
    let data = await response.json();
    // do something with data
}

获取JSON POST请求:

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify({
                property_one: value_one,
                property_two: value_two
            })
        };
let response = await fetch(url, options);
let responseOK = response && response.ok;
if (responseOK) {
    let data = await response.json();
    // do something with data
}
gc0ot86w

gc0ot86w2#

我明白了。我陷入了死循环,因为我在依赖项中添加了函数,但我学到了永远不应该这样做,而不是在依赖项中添加函数、变量、数组或原语。对我来说,我在依赖项中使用use-state(variable),而不是函数

相关问题