从 Apollo Client + React 加载完成时的回调?

Callback for when loading finishes from Apollo Client + React?

我正在使用 Apollo Client 2 和 React。查询完成加载时是否有回调?

我正在制作一个用户的帐户页面。电子邮件字段应显示用户电子邮件。我可以通过我的 graphQL 查询获取此值,但加载仅在组件已安装后完成。因此我不能使用 componentDidMount。我是否使用回调或事件来设置状态并以这种方式填充电子邮件字段?

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

class AccountPage extends React.Component {
  render() {
    if (this.props.data.loading) return <p>Loading...</p>;
    return(
    <form>
      <input type="email" />
    </form>
    )
  }
}

const UserQuery = gql`
    query UserQuery {
        user {
            _id
            email
        }
    }
`;

export default graphql(UserQuery)(AccountPage);

recompose 有一个巧妙的方法来解决这个问题:

const LoadingComponent = () => <p>Loading...</p>

compose(
  // with compose, order matters -- we want our apollo HOC up top
  // so that the HOCs below it will have access to the data prop
  graphql(UserQuery),
  branch(
    ({ data }) => {
      return !data.user && data.loading
    },
    renderComponent(LoadingComponent)
  ),
  // BONUS: You can define componentDidMount like normal, or you can use
  // lifecycle HOC and make AccountPage a functional component :)
  lifecycle({
    componentDidMount() {
    // set your state here
    },
  }),
)(AccountPage)

branch 将有条件地呈现您传递给它的任何组件 而不是包装的组件 。在这种情况下,包装组件是 compose 内部分支下的所有内容。这意味着 AccountPage 直到 data.loading 为 false 且 data.user 为真时才会挂载,这让我们可以使用 componentDidMount 根据查询结果设置状态。