我使用阿波罗客户端2与反应。当查询完成加载时,是否有回调?
我正在制作一个用户的帐户页面。电子邮件字段应该显示用户的电子邮件。我可以使用我的graphQL查询获得这个值,但是只有在组件已经挂载之后,加载才会完成。因此,我不能使用componentDidMount。是否有回调或事件,我使用setState和填充电子邮件字段的方式?
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);发布于 2018-01-31 03:32:19
有一个很好的方法可以用重组来解决这个问题
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来根据查询结果设置状态。
https://stackoverflow.com/questions/48425950
复制相似问题