从阿波罗客户端 + 反应加载完成时的回调



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

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

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);
有一种

巧妙的方法可以通过重构来解决这个问题:

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将有条件地呈现您传递给它的任何组件,而不是包装的组件。在这种情况下,包装的组件是组合内部分支下的所有内容。这意味着AccountPage直到data.loading为假而data.user为真,才被挂载,这允许我们使用 componentDidMount 根据查询结果设置状态。

最新更新