在 React 组件挂载后调用一次 GraphQL Mutation

Call a GraphQL Mutation once after React component mounts

用户创建个人资料后,他们会在电子邮件中收到 link,这会将他们发送回站点,并在 url 中收到 verifyToken。如果令牌与存储在数据库中的令牌匹配,则它们的 isVerified 状态将存储在数据库中,值为 true.

new-profile.js

import VerifyEMail from '../components/VerifyEmail';

const NewProfilePage = props => (
  <div>
    <VerifyEMail verifyToken={props.query.verifyToken} />
  </div>
);

export default NewProfilePage;

目前,我已经实现并使用带有 "Verify" 按钮的表单工作,用户必须单击该按钮才能调用 graphQL 变更 verifyEmail。由于这会将数据库中的 isVerified 值设置为 true,我知道一切正常。

../components/VerifyEmail.js

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Mutation } from 'react-apollo';
import gql from 'graphql-tag';

const VERIFY_EMAIL_MUTATION = gql`
  mutation VERIFY_EMAIL_MUTATION($verifyToken: String!) {
    verifyEmail(verifyToken: $verifyToken) {
      isVerified
    }
  }
`;

class VerifyEmail extends Component {
  render() {
    const { verifyToken } = this.props;
    return (
      <Mutation mutation={VERIFY_EMAIL_MUTATION} variables={{ verifyToken }}>
        {verifyEmail => (
          <form
            onSubmit={async () => {
              await verifyEmail(verifyToken);
            }}
          >
            <button type="submit">Verify</button>
          </form>
        )}
      </Mutation>
    );
  }
}

VerifyEmail.propTypes = {
  verifyToken: PropTypes.string.isRequired,
};

export default VerifyEmail;

但是,我真的不想强迫我的用户必须单击按钮才能触发更改。我希望在组件加载后调用它。我为此绞尽脑汁一天半,尝试了很多东西,似乎找不到任何有用的东西。

我已经看到一些使用 React hooks, Apollo hooks、componentDidMount 等的解决方案。我只是很难再看到它。这个 link 有一些我迄今为止找到的最佳解决方案,但我不知道如何实施它们...... [Feature idea] Execute a mutation on mount #1939

如果能帮我指明正确的方向,我将不胜感激。谢谢。

使用 React hooks 时,这个应用程序要简单得多:

import React, { useEffect } from "react";

function VerifyEmail({ verifyToken }) {
  const [ verifyEmail, { loading, data, error }] = useMutation(VERIFY_EMAIL_MUTATION);
  useEffect(() => {
    verifyEmail({
      variables: { verifyToken },
    });
  }, []);
  return (
    <>
      {loading && <p>Loading...</p>}
      {data && <p>Verified successfully!</p>}
      {error && <p>Error!</p>}
    </>
  )
}

如果您想继续使用 类,唯一的解决办法是创建一个组件并为此目的利用该组件的 componentDidMount

// Current component:
<Mutation mutation={VERIFY_EMAIL_MUTATION} variables={{ verifyToken }}>
  {verifyEmail => (
    <SendEmail token={verifyToken} verify={verifyEmail} />
  )}
</Mutation>

// Send Email component
class SendEmail extends Component {
  componentDidMount() {
    const { token, verify } = this.props;
    verify(token);
  }
  render() {
    return (
      //handle loading, data and error states
    )
  }
}