[英]GraphQL returns data but undefined in code
我正在使用下面的 gql 查詢發出 GraphQL 請求。
export const GET_DETAILS = gql`
query ($id: String) {
country(id: $id) {
currency
phone
}
}
`;
當我在 chrome 開發工具的網絡選項卡中檢查其響應時,我看到以下內容:
但是當我在下面的代碼中將它注銷時,它返回 undefined。
render() {
return (
<div>
<Query query={GET_DETAILS} variables={{ id: `${this.props.match.params.code}` }}>
{(loading, error, data) => {
{console.log(data)} // ----> Here it is undefined
return (
<div>
</div>
);
}}
</Query>
</div>
);
}
知道我做錯了什么以及如何解決嗎?
我有一個類似的場景。
我將 React 組件從一個項目復制到另一個項目,以及gql查詢。
const { loading, data } = useQuery<NotificationsData>(GET_NOTIFICATIONS);
這在舊項目上運行良好,而不是在新項目中。 我可以看到在網絡選項卡中返回的數據,但它在我的組件中仍未定義。 即使加載更改為false。
這是我的gql查詢
query UserDetails {
userDetails {
id
username
first_name
last_name
avatar_url
initials @client
}
}
這里的問題是這條線
initials @client
所以,我忘了在我的index.tsx文件中為@client字段添加解析器。
就像是:
const client = new ApolloClient({
cache: new InMemoryCache(),
resolvers: {
UserEntity: {
initials: (user, _args, { cache }) => {
let initials = user.first_name[0];
if (user.last_name && user.last_name.length) {
initials = initials + user.last_name[0];
}
return initials;
},
},
},
});
添加此內容后,數據開始在我的組件中正常顯示。
與所有 API 請求一樣,GraphQL 查詢是異步的,因此如果數據尚未從服務器到達,則無法記錄數據,這看起來您正在嘗試這樣做。
如果您在記錄之前檢查以確保數據存在,它將起作用。
if (data) {
console.log(data);
}
Query
組件使用的 render props 函數被傳遞一個對象作為它的第一個也是唯一的參數。 loading
、 error
和data
都是該對象的屬性。 換句話說,使用解構語法,您可以像這樣訪問它們:
{({ loading, error, data }) => {
console.log(data)
...
}
這相當於
{(props) => {
console.log(props.data)
...
}
當然,因為 GraphQL 請求是異步的,所以在請求完成之前data
將是未定義的,因此您的代碼也需要反映這一事實。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.