首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从阿波罗客户端+反应加载完成时的回调?

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

Stack Overflow用户
提问于 2018-01-24 15:22:24
回答 1查看 1.6K关注 0票数 1

我使用阿波罗客户端2与反应。当查询完成加载时,是否有回调?

我正在制作一个用户的帐户页面。电子邮件字段应该显示用户的电子邮件。我可以使用我的graphQL查询获得这个值,但是只有在组件已经挂载之后,加载才会完成。因此,我不能使用componentDidMount。是否有回调或事件,我使用setState和填充电子邮件字段的方式?

代码语言:javascript
运行
复制
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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-01-31 03:32:19

有一个很好的方法可以用重组来解决这个问题

代码语言:javascript
运行
复制
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为false,而data.user是真实的,这使得我们可以使用componentDidMount来根据查询结果设置状态。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48425950

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档