【问题标题】:Callback for when loading finishes from Apollo Client + React?从 Apollo Client + React 加载完成时回调?
【发布时间】:2018-07-03 16:52:33
【问题描述】:

我正在使用 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);

【问题讨论】:

    标签: react-apollo


    【解决方案1】:

    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 根据查询结果设置状态。

    【讨论】:

      猜你喜欢
      • 2013-06-21
      • 2010-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-15
      • 1970-01-01
      • 2019-03-30
      • 2019-08-06
      相关资源
      最近更新 更多