【问题标题】:Show Api errors with React final form and Axios使用 React 最终形式和 Axios 显示 Api 错误
【发布时间】:2020-04-15 15:46:09
【问题描述】:

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

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

我想要做的是在捕获中返回错误,例如当 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>
  );

【问题讨论】:

    标签: reactjs api error-handling axios react-final-form


    【解决方案1】:

    尝试使用async/await 语法。

    还有一种情况是,您的错误块没有被首先调用,并且控件仍在成功回调中。因此,如果状态码不是 200,您可能还想在其中放置一个 else 条件以返回错误。

    类似这样的:

    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"
        };
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2018-05-22
      • 2022-12-05
      • 2019-09-15
      • 1970-01-01
      • 2019-08-25
      • 1970-01-01
      相关资源
      最近更新 更多