【发布时间】:2020-04-18 09:01:56
【问题描述】:
我试图在 Code Sandbox 中复制我的本地项目,但我发现了我的错误。我在这些项目中尝试做的是在从 Express + GraphQL 服务器获取一些数据时显示加载器微调器,但是加载数据时加载器不会隐藏。
这是我获取数据的代码:
import React, { useEffect, useContext, useState } from "react";
import GlobalContext from "../../context/Global/context";
import gql from "graphql-tag";
import { useLazyQuery } from "@apollo/react-hooks";
const GET_USERS = gql`
query {
users {
id
name
address {
street
}
}
}
`;
export default props => {
const globalContext = useContext(GlobalContext);
const [getUsers, { called, loading, data: users }] = useLazyQuery(GET_USERS);
useEffect(() => {
getUsers();
}, []);
useEffect(() => {
console.log(globalContext.loading)
if (globalContext.loading && users.length) {
globalContext.setLoading(false);
}
}, [globalContext, users]);
if (called && loading) {
globalContext.setLoading(true);
}
if (!users) {
return <p>There are no users</p>;
}
console.log(users)
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Street</th>
</tr>
</thead>
<tbody>
{users.map(user => {
return (
<tr>
<td>{user.id}</td>
<td>{user.name}</td>
<td>{user.address.street}</td>
</tr>
);
})}
</tbody>
</table>
);
};
这是我设置加载器的代码:
import React, { useContext, useEffect } from "react";
import { ApolloClient } from "apollo-boost";
import { ApolloProvider } from "@apollo/react-hooks";
import { HttpLink } from "apollo-link-http";
import { InMemoryCache } from "apollo-cache-inmemory";
import Users from "./components/Users";
import GlobalContext from "./context/Global/context";
import Loader from "react-loader-spinner";
const cache = new InMemoryCache();
const link = new HttpLink({
uri: "https://73rcp.sse.codesandbox.io/"
});
const client = new ApolloClient({
link,
cache
});
export default () => {
const globalContext = useContext(GlobalContext);
if (globalContext.loading) {
return (
<div
style={{
width: "100vw",
height: "100vh",
display: "flex",
justifyContent: "center",
alignItems: "center"
}}
>
<Loader type="Puff" />
</div>
);
}
return (
<ApolloProvider client={client}>
<Users />
</ApolloProvider>
);
};
This is the frontend code
This is the backend code
我总是有同样的问题,不知道我做错了什么,但我想这是因为当我设置 globalContext.setLoading(true) 时,组件重新渲染并且第一个组件 App.js 加载之前比 用户组件。
如果这是否是错误,那么在从任何地方获取任何数据时设置加载器微调器的正确方法是什么?提前致谢。
【问题讨论】:
标签: javascript reactjs express graphql