我有一个简单的 React 组件,它使用 Apollo 的 useQuery
来获取数据。问题是,因为组件被渲染了两次,它调用了两次 useQuery
,然后调用了 Apollo 解析器两次,然后调用了两次获取和返回数据的关联函数,我们都可以同意不是很好。
如何阻止数据获取函数被多次调用?
数据获取函数中的一个简单的 console.log
语句表明它被调用了两次。
import { useEffect } from "react";
import { useQuery, useMutation, gql } from "@apollo/client";
import { Wrapper, Title } from "./App.styles";
const GET_SIGNALS = gql`
query {
charts {
symbol
price
}
}
`;
const App = () => {
const { loading, error, data } = useQuery(GET_SIGNALS);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error...</p>;
console.log(data);
return (
<Wrapper>
<Title>Trend List</Title>
</Wrapper>
);
};
export default App;
这里的阿波罗服务器:
import { ApolloServer, gql } from "apollo-server-micro";
import { getCharts } from "../../src/getCharts";
const typeDefs = gql`
type Chart {
symbol: String
price: [String]
}
type Query {
charts: [Chart]
}
`;
const resolvers = {
Query: {
charts: () => getCharts(),
},
};
const server = new ApolloServer({ typeDefs, resolvers });
const handler = server.createHandler({ path: "/api/graphql-api" });
export const config = {
api: {
bodyParser: false,
},
};
export default handler;
getCharts()
函数只返回一个符合类型定义的对象。
export const getCharts = async () => {
console.log("1. Starting getCharts");
return [{ symbol: "BTCUSDT", price: ["1", "2", "3"] }];
};
所以输出是:
1. Starting getCharts
1. Starting getCharts