[用户创建个人资料后,他们会在电子邮件中收到一个链接,该链接会将其发送回站点,并在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;
[目前,我已经实现并使用带有“验证”按钮的表单,用户必须单击该表单才能调用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等的解决方案。我的想法是,现在很难再看到它了。到目前为止,该链接提供了一些最佳的解决方案,但是我不知道如何实现它们。[Feature idea] Execute a mutation on mount #1939
向我指出正确方向的任何帮助,将不胜感激。谢谢。
使用React钩子时,这是简单得多的应用程序:
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
)
}
}