Graphql使用redux状态以及Apollo

时间:2017-07-18 22:34:51

标签: reactjs redux graphql apollo

我有一个服务器端呈现的应用程序,并希望在第一次渲染时可以访问数据。如果用户导航到下一页,我想使用graphQL库Apollo来获取新内容。

当请求页面时,服务器使用所请求页面的数据设置initialState键curPage。例如,用户请求http://example.com/about。我从我的数据库中获取/about的页面数据,将initialState键curPage设置为来自数据库的数据。

所以我的initialState看起来像这样:

{
  "curPage": {
    "id": 5,
    "title": "About",
    "slug": "about",
    "path": "/about",
    "template": "about",
    "published": "2017-07-10 02:02:30",
    "image": null,
    "seo": {
      "title": null,
      "description": null,
      "image": null,
      "fbAdmins": null,
      "gtm": null,
      "schema": ""
    },
    "sections": [
      {
        "type": "masthead",
        "mh_title": "",
        "video": false,
        "image": [

        ],
        "showCta": false,
        "cta": [

        ]
      },
      {
        "type": "text_image",
        "alignment": "left",
        "text_image": [
          {
            "type": "text",
            "title": "",
            "content": "",
            "call_to_action": false,
            "cta": [

            ]
          }
        ]
      }
    ]
  },
}

因此,如果curPage数据可用,我想使用它,否则我想从graphQL中获取。

我的页面组件目前仅从graphQL获取,不检查数据是否在initialState中可用。

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

import './about.css'

class About extends Component {
  render() {
    return (
      <section className='about-container'>
        <h2>About Page</h2>
      </section>
    )
  }
}

const mapQueryToProps = ({data: { findResource }, ownProps}) =>
  ({ curPage: findResource ? findResource[0] : null })

const MY_QUERY = gql`
  query {
    findResource(filter: {resource: "pages", slug: "about"}) {
        id
        title
        slug
        path
        sections
    }
  }`

 export default graphql(MY_QUERY, { props: mapQueryToProps })(About)

有没有办法通过Apollo graphQL我可以做一些像react-redux的connect()那样但是如果它不可用则从graphQL中获取?

我猜我需要使用connect()但是在我的componentDidMount()检查数据是否已设置以及是否未检索数据?

1 个答案:

答案 0 :(得分:1)

You need to transform the curData into the Apollo graphql format and use it to initialize the Apollo section of the store.

You can read about the specific here: http://dev.apollodata.com/react/server-side-rendering.html#store-rehydration

的值

请注意,Apollo实际上支持服务器端呈现,因此如果您在服务器上使用Apollo Graphql,它实际上会生成您需要发送到客户端以用于初始化客户端Redux存储的状态

相关问题