使用 React 最终形式和 Axios 显示 Api 个错误

Show Api errors with React final form and Axios

我正在尝试显示从 Api 返回的错误,使用 React Final Form 和 Axios 进行 API 调用。 当我 return 来自 Axios 的 .catch() 中的错误时,似乎表单没有重新加载错误消息。

正如您在顶部注释掉的 return 中看到的那样,如果我在那里调用它,它会在表单中正确显示错误。虽然当我在 catch() 中调用它时它没有显示任何错误。

我想要做的是 return 捕获中的错误,当 API 例如发送 400 响应时。

我的 onSubmit 如下,axiosConfig 只是一个拦截器,用于将令牌附加到 api 调用。我也用普通的 axios 测试了它,但行为是一样的。

  const onSubmit = async values => {
    //return { [FORM_ERROR]: "Login Failed" };
    axiosConfig.put('/api/v1/user/change-password/' + userPk, values, {
      'headers': { 'Authorization': auth }
    }).then( result => {
      if (result.status === 200) {
        setChanged(true);
      } 
    }).catch((error) => {
      console.log(error)
      return { [FORM_ERROR]: "Login Failed" };
    });
  };

我的表格是这样的。

  return (
    <div style={{ padding: 16, margin: 'auto', maxWidth: 650 }}>
      <Form
        onSubmit={onSubmit}
        initialValues={{  }}
        validate={validate}
        render={({ 
          submitError,
          handleSubmit,
          reset,
          submitting,
          pristine,
          values 
          }) => (
          <form onSubmit={handleSubmit} noValidate>
            <Paper style={{ padding: 16 }}>
              <Typography variant="h5" align="center" component="h2" gutterBottom>
                Passwort Ändern
              </Typography>
              {console.log(submitError)}

              <div>
                <Grid container alignItems="center" justify="center" spacing={4}>

                  <Grid item>
                    <Field 
                      fullWidth
                      required
                      margin="normal"
                      variant="outlined"
                      component={TextField}
                      name="old_password"
                      label="Altes Passwort"
                      type="password"
                    />                  
                    <Field 
                      fullWidth
                      required
                      margin="normal"
                      variant="outlined"
                      type="password"
                      name="new_password"
                      component={TextField}
                      label="Neues Password"
                    />                  
                    <Field 
                      fullWidth
                      required
                      margin="normal"
                      variant="outlined"
                      type="password"
                      name="new_password2"
                      component={TextField}
                      label="Neues Password Wiederholen"
                    />                  
                  </Grid>

                </Grid>
              </div>
              <div>
                {submitError && <div className="error">{submitError}</div>}
                <Grid container alignItems="flex-start" justify="space-between" spacing={4}>

                  <Grid item xs container spacing={4}>
                    <Grid item style={{ marginTop: 16 }}>
                      <Button
                        component={ Link }
                        to="/account/information"
                        type="button"
                        variant="contained"
                      >
                        Zurück
                      </Button>
                    </Grid>
                    <Grid item style={{ marginTop: 16 }}>
                      <Button
                        variant="contained"
                        color="primary"
                        type="submit"
                      >
                        Speichern
                      </Button>
                    </Grid>
                  </Grid>


                </Grid>
              </div>
            </Paper>
          </form>
        )}
      />
    </div>
  );

尝试使用 async/await 语法。

也有可能是你的错误块一开始没有被调用,而控件仍在成功回调中。因此,如果状态代码不是 200,您可能还想在其中放置一个 else 条件 return 一个错误。

像这样:

const onSubmit = async values => {
  try {
    const result = await axiosConfig.put('/api/v1/user/change-password/' + userPk, values, {
      'headers': {
        'Authorization': auth
      }
    });

    if (result.status === 200) {
      setChanged(true);
    } else {
      // You Might also want to try this!
      return {
        [FORM_ERROR]: "Login Failed"
      };
    }
  } catch (error) {
    console.log(error)
    return {
      [FORM_ERROR]: "Login Failed"
    };
  }
};