单击两次提交按钮,React Formik onSubmit RestAPI被调用两次

时间:2019-06-21 12:38:08

标签: reactjs formik

当我单击“提交”按钮并触发onSubmit事件时,我正在使用Formik和Yup进行响应,并且在事件内部,提取函数调用了两次,

import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import Container from '@material-ui/core/Container';
import { TextField } from 'formik-material-ui';
import { Formik, Field, Form } from 'formik';
import * as Yup from 'yup';
class LoginForm extends Component {
    constructor(props) {
        super(props);
        this.state = {classes: this.props.classes, isLoading: false }
    }
render() {
   return (
        <Formik
            initialValues={initialFormValues}
            validationSchema={validationFrom}
            onSubmit={(values, actions) => {
                this.setState({ isLoading: true });
                console.log(values);
                actions.setSubmitting(false);
                console.log('SUCCESS!! :-)\n\n' + JSON.stringify(values, null, 2));

                fetch('http://xx.xx.xx.xx.compute-1.amazonaws.com:9000/api/v1/userAuth', {
                    method: 'POST',
                    headers: {
                        'Accept': 'application/json',
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(values)
                })
                    .then(Response => {
                        console.log(Response);
                        this.setState({ isLoading: false });
                    })
               }
            }
            render={({ submitForm, isSubmitting, isValid }) => (
                <Form>
                    <Container component="main" maxWidth="xs" >
                        <div className={this.state.classes.paper}>
                            <Field
                                variant="outlined" margin="normal" fullWidth label="User ID" name="userid" id="userid" type="text"
                                autoComplete="userid" component={TextField} />
                            <Field
                                variant="outlined" margin="normal" fullWidth id="password" name="password" label="Password" type="password"
                                autoComplete="current-password" component={TextField} />

                            <Button
                                type="submit" fullWidth variant="contained" color="primary"
                                    className={this.state.classes.submit} disabled={isSubmitting || !isValid}
                                > Sign In
                            </Button>
                        </div>
                    </Container>
                </Form>
            )}
        />
    )
 }
}
export default LoginForm;

我是React的新手,我在Google上搜索它,但是没有运气,这是我尝试过的代码,我调用了用于用户身份验证的API来验证userId和密码,请建议我采取正确的方法来调用API。

enter image description here

1 个答案:

答案 0 :(得分:3)

我看到第一个调用是0个字节。

尽管我看不到您的 XHR 通话的详细信息,但是恕我直言,第一个通话不是 POST 动词,而是 OPTION

OPTION 调用中,服务器根据 CORS 授权或拒绝对端点的访问。因此,我认为这并不奇怪。