New to react, useEffect not working how I would expect with utility functions

huangapple go评论54阅读模式
英文:

New to react, useEffect not working how I would expect with utility functions

问题

以下是您要翻译的内容:

首先,我是React的新手。这个问题让我感到很头疼...

尝试获取并显示项目列表:

// Things.jsx

//导入...
 

export default function Things() {
  const [things, setThings] = useState([]);
  useEffect(() => {  
      // 启用请求取消
      ThingsAPI.getAll().then((things) => {
          setThings(things)
          console.log("setThings(things) = " + things)
      })
}, [])

  return (
    <div>
      <Heading>Things</Heading>
      <Divider p="10px" />
      <Spacer p="10px" />
      { things && <ThingsList things={things} title="All The Things" /> }
    </div>
  )
}

然后我有一个API类...

// ThingsAPI.js

import React from 'react'
import { get } from 'react-hook-form';

const URL_STRING="http://localhost:8888/things"

export const ThingsAPI = {
    getAll: async function() {
        fetch(URL_STRING)
            .then((response) => {
                
                console.log("return response.json()")
                return response.json();
            })
            .then( data => {
                console.log("return data")
                return data
            })
    },

    get: async function(thingId) {
      // 待办事项
    }
}

查看我的控制台,我得到...

setThings(things) = undefined
return response.json()
return data

所以,问题是页面最初不显示任何内容,因为things常量为空。但当ThingsAPI中的getAll()函数返回数据时... 它永远不会传递到页面中的setThings()。

如果我将fetch调用从实用程序类移到页面上的useEffect中,一切都正常工作。

我一定是错过了一些明显的东西,因为我只学React几天。任何指导都将不胜感激。

英文:

First of all, new to react. Been banging my head against the desk with this one..

Trying to fetch and display a list of items:

// Things.jsx

//imports...
 

export default function Things() {
  const [things, setThings] = useState([]);
  useEffect(() =&gt; {  
      // enabling request cancellation
      ThingsAPI.getAll().then((things) =&gt; {
          setThings(things)
          console.log( &quot;setThings(things) = &quot; + things)
      })
}, [])

  return (
    &lt;div&gt;
      &lt;Heading&gt;Things&lt;/Heading&gt;
      &lt;Divider p=&quot;10px&quot; /&gt;
      &lt;Spacer p=&quot;10px&quot; /&gt;
      { things &amp;&amp; &lt;ThingsList things={things} title=&quot;All The Things&quot; /&gt; }
    &lt;/div&gt;
  )
}

and I have an API class...

// ThingsAPI.js

import React from &#39;react&#39;
import { get } from &#39;react-hook-form&#39;;

const URL_STRING=&quot;http://localhost:8888/things&quot;

export const ThingsAPI = {
    getAll: async function() {
        fetch(URL_STRING)
            .then((response) =&gt; {
                
                console.log(&quot;return response.json()&quot;)
                return response.json();
            })
            .then( data =&gt; {
                console.log(&quot;return data&quot;)
                return data
            })
    },

    get: async function(thingId) {
      // todo
    }
}

And looking at my console, I get...

setThings(things) = undefined
return response.json()
return data

So, what's happening is that the page doesn't initially display anything, because the things const is empty. But when the getAll() function in ThingsAPI returns data.. it never makes it to the setThings() in the page.

If I move the fetch call out of the utility class, and into the useEffect on the page, it all works.

I've got to be missing something right in front of me, that I just don't get because i'm only a couple of days into React.

Any guidance would be appreciated

答案1

得分: 1

ThingsAPI内部定义的getAll方法中,你没有返回fetch调用返回的Promise。因此,在useEffect中的ThingsAPI.getAll().then(...)实际上并不等待响应的到达。

只需添加一个return语句来修复这个问题。注意,你不需要将此方法标记为async,因为你在其中没有使用await

  getAll: function () {
    return fetch(URL_STRING)
      .then(response => {
        console.log('return response.json()');
        return response.json();
      })
      .then(data => {
        console.log('return data');
        return data;
      });
  },
英文:

In the getAll method defined inside ThingsAPI, you are not returning the Promise returned by the fetch call. Because of this, ThingsAPI.getAll().then(...) inside the useEffect does not actually wait for the response to be received.

Simply add a return to fix this. Notice that you don't need to mark this method as async, since you're not using await inside it.

  getAll: function () {
    return fetch(URL_STRING)
      .then(response =&gt; {
        console.log(&#39;return response.json()&#39;);
        return response.json();
      })
      .then(data =&gt; {
        console.log(&#39;return data&#39;);
        return data;
      });
  },

huangapple
  • 本文由 发表于 2023年5月18日 01:15:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274636.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定