正在等待React组件中的异步函数&显示Spinner



这里是初学者。

尝试从服务器获取一些数据,并在获取后将其显示在我的react组件中。然而,我在将异步函数集成到我的react组件中时遇到了问题。

import React, { useState } from "react";
import { request } from "graphql-request";
async function fetchData() {
const endpoint = "https://localhost:3090/graphql"
const query = `
query getItems($id: ID) {
item(id: $id) {
title
}
}
`;
const variables = {
id: "123123123"
};
const data = await request(endpoint, query, variables);
// console.log(JSON.stringify(data, undefined, 2));
return data;
}
const TestingGraphQL = () => {
const data = fetchData().catch((error) => console.error(error));
return (
<div>
{data.item.title}
</div>
);
};
export default TestingGraphQL;

我想在等待时简单地展示一个旋转器或其他东西,但我尝试了这个&似乎是因为得到了回报,我不能这样做。

这里需要使用useEffect钩子来调用API。从API返回的data,我在这里存储为一种状态,以及loading状态,以指示何时进行调用。

遵循下面代码之间添加的注释-

代码

import React, { useState, useEffect } from "react"; // importing useEffect here
import Layout from "@layouts/default";
import ContentContainer from "@components/ContentContainer";
import { request } from "graphql-request";
async function fetchData() {
const endpoint = "https://localhost:3090/graphql"
const query = `
query getItems($id: ID) {
item(id: $id) {
title
}
}
`;
const variables = {
id: "123123123"
};
const data = await request(endpoint, query, variables);
// console.log(JSON.stringify(data, undefined, 2));
return data;
}
const TestingGraphQL = () => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);

// useEffect with an empty dependency array works the same way as componentDidMount
useEffect(async () => {
try {
// set loading to true before calling API
setLoading(true);
const data = await fetchData();
setData(data);
// switch loading to false after fetch is complete
setLoading(false);
} catch (error) {
// add error handling here
setLoading(false);
console.log(error);
}
}, []);
// return a Spinner when loading is true
if(loading) return (
<span>Loading</span>
);
// data will be null when fetch call fails
if (!data) return (
<span>Data not available</span>
);
// when data is available, title is shown
return (
<Layout>
{data.item.title}
</Layout>
);
};

因为fetchData()返回了一个promise,所以您需要在TestingGraphQL中处理它。我建议onComponentMount进行数据调用。将检索到的数据设置到state变量中,以便react跟踪数据调用并在数据调用完成时重新渲染。

我添加了一个加载状态变量。如果loading为true,则它显示"loading",否则它显示数据。您可以稍后将其更改为组件,以满足您的需求。

请参阅下面的示例,从钩子切换到类,但您应该能够使其工作!:(

class TestingGraphQL extends Component {
constructor() {
super();
this.state = { data: {}, loading: true};
}

//when the component is added to the screen. fetch data
componentDidMount() {
fetchData()
.then(json => { this.setState({ data: json, loading: false }) })
.catch(error => console.error(error));
}

render() {
return (
{this.state.loading ? <div>Loading Spinner here</div> : <div>{this.state.data.item.title}</div>}
);
}
};

最新更新