簡體   English   中英

React + Apollo:GraphQL錯誤數組未傳遞到組件中

[英]React + Apollo: GraphQL errors array not passed into component

根據這些Apollo 文檔 ,設置allerror-policy應該使我的Apollo包裝的React組件可以使用GraphQL響應的errors數組“所以[我的] UI可以使用它們。” 我的應用程序是通用的,因此我使用此策略非常重要,因此錯誤不會阻止應用程序完全呈現。

問題是,即使我的瀏覽器開發工具在服務器響應中顯示errors數組,我也無法在我的React組件的道具中訪問它。 同樣, props.data.error總是未定義的。 為什么是這樣?

// Component
import React from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';

const Cart = (props) => {
  console.log(props.errors); // undefined
  console.log(props.data.error); // undefined
  console.log(props.data.cart); // null

  return <div>Foo.</div>;
};

export default graphql(gql`
  query CartQuery {
    cart {
      products {
        _id,
        name
      }
    }
  }
`, { options: { errorPolicy: 'all' } })(Cart);


// Resolver
cart: (root, args, context) => {
  throw new Error('foo');
}


// Browser network tab response
{"data":{"cart":null},"errors":[{"message":"foo","locations":[{"line":2,"column":3}],"path":["cart"]}]}

undefined表示沒有錯誤,因此您成功獲取了在屏幕上顯示組件時遇到問題的數據,因為從graphQL服務器獲取數據是異步操作。 如果你

       console.log(props)

您將在控制台中看到2個數據對象。 在第一個中,data.loading:true

這意味着正在進行提取並且還沒有返回。 因此,在渲染組件時,組件將無法顯示任何內容。

如果你檢查第二個數據對象,你會看到

data.loading:false

這意味着解析已解決,如果成功解決,您將看到

data.QueryCart: "response will be here"

如果promise被拒絕,你會有data.error填充錯誤消息

所以你應該做的是實現一個條件渲染。

if(props.data.loading){
        return (
            <div>Loading</div>
        )
    }
return <div>Foo.</div>

一旦props.data.loading變為false,則return <div>Foo.</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM