这里的初学者。
尝试从服务器获取一些数据,并在获取数据后显示在我的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;我想在等待的时候简单地展示一个旋转器或什么东西,但我尝试了这一点&似乎是因为一个承诺得到了回报,所以我不能这样做。
发布于 2020-07-31 13:14:12
在这里,您需要使用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>
);
};发布于 2020-07-31 13:16:38
因为fetchData()返回一个承诺,所以您需要在TestingGraphQL中处理它。我建议onComponentMount做您的数据调用。将检索到的数据设置到state变量中,以便在数据调用完成后对数据进行跟踪和重新呈现。
我添加了一个加载状态var。如果加载为真,则显示“加载”,否则会显示数据。您可以在以后将这些更改为组件,以适应您的需要。
参见下面的示例,从钩子切换到类,但是您应该能够使它工作!:)
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>}
);
}
};https://stackoverflow.com/questions/63192407
复制相似问题