0

我正在使用useFormik钩子将 Formik 与我的表单一起使用。在我设置的配置中validateonSubmitinitialValues键。我想清理我的输入,比如修剪和转义。对于电子邮件,我也想使用normalizeEmailfrom validator.js。我无法找到将清理代码放在哪里 - 我是把它放在 formik 配置中还是放在验证函数中。我意识到我可以setFieldValue从 formik 使用,但我不想更改formik.handleChange功能,因为它处理表单状态并且不想搞砸。

这是代码:

import { useEffect, useRef } from "react";
import { useSelector, useDispatch } from "react-redux";
import { NavLink as RouterLink, useHistory, useLocation } from "react-router-dom";
import Helmet from "react-helmet";
import {
    Button,
    LinearProgress,
    Typography,
    Paper,
    Grid,
    Box,
    TextField
} from "@material-ui/core";
import useMediaQuery from "@material-ui/core/useMediaQuery";
import { useFormik } from "formik";
import { useSnackbar } from "notistack";
import CenterLayout from "../CenterLayout";
import { logInUser } from "../../features/user/userSlice";
import { useTheme } from "@material-ui/core/styles";
import { useTranslation } from "react-i18next";
import isEmail from 'validator/es/lib/isEmail';

const Login = () => {
    const { isLoadingLogin, errorLoginCode } = useSelector((state) => state.user);
    const prevIsLoadingLoginRef = useRef();
    const dispatch = useDispatch();
    const history = useHistory();
    const location = useLocation();
    const theme = useTheme();
    const isXS = useMediaQuery(theme.breakpoints.down("xs"));
    const { enqueueSnackbar } = useSnackbar();
    const { t } = useTranslation();

    const formik = useFormik({
        initialValues: {
            email: "",
            password: "",
        },
        onSubmit: (values) => {
            dispatch(logInUser(values));
        },
        validate: (values) => {
            const errors = {};
            if (!values.email) {
                errors.email = t('form.required');
            } else if (
                !isEmail(values.email)
            ) {
                errors.email = t('loginPage.invalidEmail');
            }

            if (!values.password) {
                errors.password = t('form.required');
            }
            return errors;
        },
    });

    useEffect(() => {
        if (prevIsLoadingLoginRef.current && !isLoadingLogin) {
            if (errorLoginCode.length === 0) {
                formik.resetForm();
                enqueueSnackbar(t("loginPage.loginSuccess"), {
                    variant: "success",
                });
                const { from } = location.state || { from: { pathname: "/dashboard" } };
                history.replace(from);
            } else {
                enqueueSnackbar(
                    `${t("loginPage.loginFailed")}: ${t("api." + errorLoginCode)}`,
                    { variant: "error" }
                );
            }
        }

        prevIsLoadingLoginRef.current = isLoadingLogin;
    }, [
        isLoadingLogin,
        errorLoginCode,
        history,
        location,
        formik,
        enqueueSnackbar,
        t,
    ]);

    console.log("dbg1", formik);


    return (
        <CenterLayout>
            <Helmet title="Circuittutor - Login" />
            <Grid item xs={12} sm={8} md={4}>
                <Paper elevation={isXS ? 0 : 1}>
                    <Box p={2}>
                        <Typography
                            variant="h6"
                            align="center"
                            color="secondary"
                            gutterBottom
                        >
                            {t("loginPage.form")}
                        </Typography>
                        <form onSubmit={formik.handleSubmit}>
                            <TextField
                                name="email"
                                type="email"
                                label={t("loginPage.email")}
                                fullWidth
                                style={{ marginBottom: theme.spacing(2) }}
                                value={formik.values.email}
                                onChange={formik.handleChange}
                                onBlur={formik.handleBlur}
                                error={
                                    formik.touched.email &&
                                    Boolean(formik.errors.email)
                                }
                                helperText={
                                    formik.touched.email && formik.errors.email
                                }
                            />

                            <TextField
                                name="password"
                                type="password"
                                label={t("loginPage.password")}
                                fullWidth
                                style={{ marginBottom: theme.spacing(2) }}
                                value={formik.values.password}
                                onChange={formik.handleChange}
                                onBlur={formik.handleBlur}
                                error={
                                    formik.touched.password &&
                                    Boolean(formik.errors.password)
                                }
                                helperText={
                                    formik.touched.password && formik.errors.password
                                }
                            />

                            {isLoadingLogin && (
                                <LinearProgress style={{ marginBottom: theme.spacing(2) }} />
                            )}

                            <Button
                                variant="contained"
                                color="secondary"
                                disabled={isLoadingLogin}
                                type="submit"
                                fullWidth={isXS}
                            >
                                {t("form.submit")}
                            </Button>
                        </form>
                        <Button
                            exact
                            variant="text"
                            disableElevation
                            color="primary"
                            component={RouterLink}
                            to="/forgotPassword"
                            style={{ marginTop: theme.spacing(2), padding: 0 }}
                        >
                            {t('loginPage.forgotPasswordBtn')}
                        </Button>
                    </Box>
                </Paper>
            </Grid>
        </CenterLayout>
    );
};

export default Login;
4

1 回答 1

0

您需要做的就是拦截输入字段上的 onChange 事件,执行清理逻辑,然后setFieldValue使用新的计算值调用帮助程序。您无需担心与 Formik 内部相关的任何事情 - 这是提供自定义输入处理程序的官方方式

于 2021-07-26T22:20:10.063 回答