简体   繁体   English

API 不会返回数据

[英]API won't return data

I'm trying to call API when I'm in the page that show data for the specific Profile.当我在显示特定配置文件的数据的页面中时,我试图调用 API。

The url looks like: localhost:8000/profile/223网址如下: localhost:8000/profile/223

API also require to be called api/profile/223 API 也需要调用api/profile/223

The way that I'm trying to call the API is:我试图调用 API 的方式是:

const ProfileLayout = () => {
    const [profileId, setProfileId] = useState();

    useEffect(() => {
        fetch('api/profile/id')
        .then(result => {
            setProfileId(result.id);
        });
    }, [id])
    };

Fetch requires you to return the format of data from the Response object before you can use the data. Fetch 要求您在使用数据之前从 Response 对象返回数据的格式。 Use response.json() to get the JSON from your request.使用response.json()从您的请求中获取 JSON。

And like @Adriana6 mentioned, add the / to the start of your URL.就像提到的@Adriana6 一样,将/添加到 URL 的开头。

Use the profileId to inject the value into the URL string.使用profileId将值注入 URL 字符串。

useEffect(() => {
  fetch('/api/profile/${profileId}')
    .then(response => response.json())
    .then(result => {
      setProfileId(result.id);
    });
}, []);

I don't have a lot of experience in React.js but learned how to do this by reading this article on how to make fetch requests with React Hooks.我在 React.js 方面没有很多经验,但是通过阅读这篇关于如何使用 React Hooks 发出fetch请求的文章,我学会了如何做到这一点 I suggest that you look into it as well.我建议你也研究一下。

Please write the full url like localhost:8000/profile/${id} in your fetch function parameter.请在您的 fetch 函数参数中写入完整的 url,如localhost:8000/profile/${id} Then parse it as json.然后解析为json。

On the other hand, you don't have any id field.另一方面,您没有任何 id 字段。 So, using id in you useEffect will not be triggered at all.因此,在 useEffect 中使用 id 根本不会被触发。 If you want it to be triggered on page load then use如果您希望在页面加载时触发它,请使用

useEffect(() => {
    // fetch
}, [])

instead of代替

useEffect(() => {
    // fetch
}, [id])

Or you can change id with profileId .或者您可以使用profileId更改id In that case, you have to check if profileId is truthy (not null) before fetchin profile data在这种情况下,您必须在获取配置文件数据之前检查profileId是否为真(非空)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM