在页面加载时触发React Apollo突变

时间:2019-05-30 07:17:56

标签: reactjs react-apollo

我正在尝试在react-apollo应用程序中实施电子邮件验证系统,并遇到问题。问题是当用户访问带有验证令牌的链接时,我想在页面加载时触发GraphQL突变。当前,该突变是在单击按钮时触发的,但我希望它在页面加载时发生。

我试图从render返回突变,但是它使应用程序陷入无限循环。

return (
            <Mutation
              mutation={VERIFY_EMAIL_MUTATION}
              variables={{ id }}
              onCompleted={() => this.setState({ userVerified: true })}
            >
              {(verifyEmail, { loading, error }) => {
                 verifyEmail();
            }
            </Mutation>

如何实现在页面加载时触发此突变?

1 个答案:

答案 0 :(得分:0)

使用compose并将其作为函数传递给您的组件。以下方法允许您传递多个突变/查询,您可以在不使用触发器的情况下随时使用它们。

import React from "react";
import { compose, graphql } from "react-apollo";

import {
  VERIFY_EMAIL_MUTATION
} from "../GraphqlQueries/ServerQueries";

class YourComponent extends React.Component {
  componentWillMount() {
    this.props.verifyEmail({variables: {email: "your_email", variable2: "variable2" }});
  }

  render() {
    return (
      <React.Fragment>
        Your Render
      </React.Fragment>
    );
  }
}

export default compose(
  graphql(VERIFY_EMAIL_MUTATION, {
    name: "verifyEmail"
  })
)(YourComponent);