React Relay 實現

React客戶端調用GraphQL

1、經過Relay框架中的QueryRenderer組件實現數據交互,有2點須要注意一下:

1.query的命名:
注意query前綴保持和js文件名一致,ex:
App.js 命名 AppRankTypeQuery
2.schema.graphql文件的編寫
經過yarn run Relay預編譯
注意保持各類type不缺失,ex:react

type RankType implements Node {
    typeId: ID!
    typeName: String
    siteId: Int
    state: Int
    createtime: DateTime
    id: ID!
    rankList(totalCount: Int): [Rank]
}

query語句:json

const AppRankTypeQuery= graphql`
query AppRankTypeQuery($rankTypeId: ID = 1, $totalCount: Int, $withBookTypeName: Boolean = false, $withSummary: Boolean = false){
  rankType(rankTypeId: $rankTypeId) {
    typeId
    typeName
    rankList(totalCount: $totalCount) {
      rankTypeId
      book {
        bookId
        bookName
        cover
        banner
        summary @include(if: $withSummary)
        bookType @include(if: $withBookTypeName) {
          typeName
        }
        author
      }
      sort
    }
  }
}
`

QueryRenderer實現app

<QueryRenderer
  environment={xenvironment}
  query={appRankTypeQuery}
  variables={{
    totalCount: 4
  }}
  render={({error, props}) => {
    if (error) {
      console.log(error)
      return <div>Error!</div>;
    }
    if (!props) {
      return (<div>Loading</div>);
    }
    return (<div>props.data</div>);
  }}
/>

2、經過fetch直接調用

query語句:框架

const gridCardBookTypesQuery = `
query gridCardBookTypesQuery($rootId: Int=0, $totalCount: Int=12){
    bookTypeList(parentTypeId: $rootId){
      typeId
      typeName
      children(totalCount: $totalCount){
        typeId
        typeName
        parentTypeId
      }
    }
  }
`

fetch實現:fetch

componentDidMount() {
        fetch('http://localhost:5000/graphql', {
            method: 'POST',
            headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              query: gridCardBookTypesQuery,
              variables: {
                parentTypeId: this.props.typeId
              }
            }),
          }).then(response => {
            return response.json(); 
        }).then((json) => {
            this.setState({isLoading: false, value: json.data.bookTypeList});
        }).catch(function(ex) {
                console.log('request failed', ex);  //異常處理
        });
    }
相關文章
相關標籤/搜索