【问题标题】:Why is the email arriving empty in my email validation function?为什么在我的电子邮件验证功能中到达的电子邮件是空的?
【发布时间】:2021-07-01 16:46:46
【问题描述】:

一天多来我一直在分析这段代码并测试了几件事,但我仍然无法解决以下问题:

“为什么我的电子邮件验证功能中的电子邮件是空的?”

import { useState } from 'react';
import { FirestoreProvider, FirestoreMutation } from "@react-firebase/firestore";
import 'firebase/firestore';
import firebase from "firebase/app";
import '@firebase/analytics';

const config = {
    ...
};

export default function TextInput(){

    const [email, setEmail] = useState("");
    const collectionPath = "leads";
    
    async function Submit(runMutation){
        await runMutation({email});
    }

    function validateEmail(email) {
        const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(String(email).toLowerCase());
    }

    function ValidateAndSubmit(runMutation){
        if(validateEmail(email)){
            Submit(runMutation);
        }else{
            alert("Please type a valid email!");
        }
    }

    function onKeyPress(key){
        if(key === "Enter"){
            ValidateAndSubmit();
        }
    }

    return <FirestoreProvider {...config} firebase={firebase}>
                <input type="email"
                    placeholder="Type your e-mail to receive early access to the product"
                    style={{width : 500, marginRight : 10}}
                    onKeyPress={event => onKeyPress(event.key)}
                    onChange={e => {
                        e.preventDefault();
                        setEmail(e.target.value)
                    }
                    }/>
                <FirestoreMutation path={collectionPath} type="add">
                    {({ runMutation }) => (
                        <input type="submit" value="Submit" onClick={_ => ValidateAndSubmit(runMutation)}/>
                    )}
                </FirestoreMutation>
            </FirestoreProvider>
}

谁能确定问题出在哪里?

【问题讨论】:

  • 您检查控制台错误了吗?
  • 控制台没有错误。
  • 在按键时你传递ValidateAndSubmit() 不带参数但在函数中你有runmutation 参数。
  • 是的,这可能会使代码在键盘快捷键部分不起作用,但我现在没有使用该部分,我只是使用提交按钮
  • {({ runMutation }) =&gt; ... 是如何调用的?

标签: reactjs react-hooks react-functional-component


【解决方案1】:

{ email } 不是有效的表示法。

我建议你写:

async function Submit(runMutation){
        await runMutation(email);
}

或者

async function Submit(runMutation){
 await runMutation({ email : email});
}

【讨论】:

  • 这是一个完全有效的符号,称为解构赋值:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 如果我错了,但 email 是一个字符串,请纠正我,然后如果 email 是一个复杂的字符串,{ email } 不起作用
  • 这取决于runMutation 期望的参数。如果是runMutation(param: string),那么你是对的。如果是runMutation(param: {email: string}),方法完全没问题。
猜你喜欢
  • 2011-04-22
  • 2021-10-04
  • 2023-03-29
  • 2011-01-09
  • 2017-02-03
  • 1970-01-01
  • 2017-02-27
  • 1970-01-01
  • 2014-05-13
相关资源
最近更新 更多