我有一个removeUser页面,我在其中使用,然后使用submitForm()函数进行错误处理。这段代码运行良好:

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved ,setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  function StatusMessage(){
    if (isRemoved){
      return (
      <CustomAlert severity='success' text='User Removed'></CustomAlert>
        )
      }
   //else...
  }

  function submitForm(RemoveUserMutation: any, email: string) {
    setIsSubmitted(true);
      RemoveUserMutation({
        variables: {
            email: email,
        },
    }).then(({ data }: any) => {
      setIsRemoved(true);
    })
    .catch((error: { message: string; }) => {
      setIsRemoved(false);
      console.log("Error msg:" + error.message);
      setErrorMessage(error.message)
    })
  }

  return (
    <Mutation mutation={RemoveUserMutation}
    >
      {(RemoveUserMutation: any) => (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        initialValues={{ email: '' }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
        }}
        validationSchema={schema}
      >
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched
          } = props;
          const change = (name: string, e: any) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
          };
          return (
            <div className='main-content'>
              <form style={{ width: '100%' }}
               onSubmit={e => {e.preventDefault();
                submitForm(RemoveUserMutation, email)}}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ""}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, "email")}
                  />
                  <br></br>
                  <Button
                  type="submit"
                  disabled={!isValid || !email}
                  >
                    Remove User</Button>
                </div>
              </form>
              <br></br>
              {isSubmitted && StatusMessage()}
            </div>
          )
        }}
      </Formik>
    </div>
      )}
     </Mutation>
  );
}


但是,建议我使用useMutation代替。首先,由于出现以下错误,我无法这样做:

Unhandled Rejection (Error): GraphQL error: Variable `email` of type `String!` must not be null.


即使该突变有效,我仍然可以通过任何方式修改并使用相同的函数进行错误处理吗?

这是我现在正在尝试的方法,但这不起作用:

export default function RemoveUserPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved ,setIsRemoved] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  const [removeUser] = useMutation(RemoveUserMutation);

  function StatusMessage(){
    if (isRemoved){
      return (
      <CustomAlert severity='success' text='User Removed'></CustomAlert>
        )
      }
  }

  function submitForm(RemoveUserMutation: any, email: string) {
    setIsSubmitted(true);
      RemoveUserMutation({
        variables: {
            email: email,
        },
    }).then(({ data }: any) => {
      setIsRemoved(true);
    })
    .catch((error: { message: string; }) => {
      setIsRemoved(false);
      setErrorMessage(error.message)
    })
  }

  return (
    <div>
      <PermanentDrawerLeft></PermanentDrawerLeft>
      <Formik
        initialValues={{ email: '' }}
        onSubmit={(values, actions) => {
          setTimeout(() => {
            alert(JSON.stringify(values, null, 2));
            actions.setSubmitting(false);
          }, 1000);
        }}
        validationSchema={schema}
      >
        {props => {
          const {
            values: { email },
            errors,
            touched,
            handleChange,
            isValid,
            setFieldTouched
          } = props;
          const change = (name: string, e: any) => {
            e.persist();
            handleChange(e);
            setFieldTouched(name, true, false);
          };
          return (
            <div className='main-content'>
              <form style={{ width: '100%' }}
               onSubmit={e => {e.preventDefault();
                removeUser({variables: {todo: email }});}}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={touched.email ? errors.email : ""}
                    error={touched.email && Boolean(errors.email)}
                    label="Email"
                    value={email}
                    onChange={change.bind(null, "email")}
                  />
                  <br></br>
                  <Button
                  type="submit"
                  disabled={!isValid || !email}
                  >
                    Remove User</Button>
                </div>
              </form>
              <br></br>
              {isSubmitted && StatusMessage()}
            </div>
          )
        }}
      </Formik>
    </div>
  );
}

最佳答案

不再需要RemoveUserMutation了-removeUser已经在范围内,因此只需使用它即可。

function submitForm(email: string) {
  setIsSubmitted(true);
  removeUser({
    variables: {
      email,
    },
  })
  ...
}


您可以像这样继续使用submitForm函数:

onSubmit={e => {
  e.preventDefault();
  submitForm(email);
}}


这条线

removeUser({variables: {todo: email }})


无法工作,因为没有todo变量。由于使用TypeScript,因此应为查询生成类型定义,然后将其与挂钩一起使用。这样可以避免这样的错误。

09-07 17:37