如何从 url 获取电子邮件 ID?

How to fetch email id from url?

我创建了一个 formik 表单,其中的初始值是从 URL 中获取的。我正在尝试从 URL 中获取电子邮件 ID 和公司名称。我正在使用 react-hooks 通过 useEffect 获取数据。我已尝试使用电子邮件,但无法获取

例如URL = 'https://abc.xyz.com/?abcxyz@gmail.com&abccampaign=email%data%abcpvtltd%'

代码:

// @ts-ignore

import React, { useState, useEffect } from 'react';
import { Formik, Form, Field } from 'formik';
import { Typography, Button, Grid } from '@material-ui/core';
import * as Yup from 'yup';
import { MyInput } from './comman/MyInput';
import { Textarea } from './comman/Textarea';
import { Event } from '../Tracking/Event';

const contactSchema = Yup.object().shape({
  name: Yup.string().required('Please Enter Your Name'),
  email: Yup.string()
    .email('Please enter a valid email address')
    .required('Please enter an email address'),
  number: Yup.string()
    .min(10, 'Must be 10 digit.')
    .max(10, 'Must be 10 digit.'),
});
export default function ContactUs(props: any) {
  const [state, setState] = useState({
    msg: '',
  });
  const [selectedemail, setEmail] = useState({
    text: '',
  });

  useEffect(() => {
    const findemail = window.location.href;
    //const findemail =
    //  'https://abc.xyz.com/?abcxyz@gmail.com';
    console.log('url', findemail);

    const finalemail = findemail.split('?');
    //const emails = finalemail[1].split('&');

    const email = finalemail[1].toString();
    console.log(email);
    console.log(setEmail({ text: email }));
    console.log(selectedemail.text);
  }, []);

  return (
    <div>
      <img
        src="public/abc.png"
        width="200"
        className="d-inline-block"
        alt="Viser"
        style={{
          marginTop: '2em',
          marginBottom: '2em',
          float: 'right',
        }}
      />
      <Formik
        initialValues={{
          name: '',
          email: selectedemail.text,
          number: '',
          companyname: '',
          message: '',
        }}
        validationSchema={contactSchema}
        onSubmit={(values, { resetForm }) => {
          const data = {
            name: values.name,
            email: values.email,
            number: values.number,
            companyname: values.companyname,
            message: values.message,
            formtype: 'Contactus',
          };
          console.log(data);
          const request = new Request(
            `${process.env.REACT_APP_PRODUCTION_EMAILCONTACTUS_API}`,
            {
              method: 'POST',
              headers: new Headers({
                'Content-Type': 'application/json',
              }),
              body: JSON.stringify(data),
            },
          );

          fetch(request)
            .then((res) => res.json())
            .then((data) => {
              if (
                data.message ===
                'Thanks!'
              ) {
                setState({
                  msg: data.message,
                });
              } else {
                console.log('error');
              }
            });
          resetForm();
        }}
      >
        {({ errors, touched }) => (
          <Grid container>
            <Grid item xs={12}>
              <Typography
                variant="body1"
                style={{
                  marginTop: '1em',
                  fontFamily: 'roboto',
                  fontSize: '1.3rem',
                  color: '#2F4858',
                }}
              >
                To know more please submit your information, and one of our
                expert advisors will get in touch within 24 hours!{' '}
              </Typography>
              <br />

              <Form>
                <Typography
                  variant="h6"
                  style={{
                    fontFamily: 'roboto',
                    color: '#2F4858',
                    marginTop: '0.5em',
                  }}
                >
                  Full Name
                </Typography>
                <Field
                  id="outlined-multiline-flexible"
                  type="text"
                  name="name"
                  placeholder="Name"
                  component={MyInput}
                />
                <br />
                {errors.name && touched.name ? (
                  <div className="text-danger" style={{ color: 'red' }}>
                    {errors.name}
                  </div>
                ) : null}
                <Typography
                  variant="h6"
                  style={{ fontFamily: 'roboto', marginTop: '1em' }}
                >
                  Email
                </Typography>
                <Field
                  type="email"
                  name="email"
                  placeholder="Email"
                  values={props.text}
                  style={{ color: 'white' }}
                  component={MyInput}
                />{' '}
                <br />
                {errors.email && touched.email ? (
                  <div className="text-danger" style={{ color: 'red' }}>
                    {errors.email}
                  </div>
                ) : null}
                <Typography
                  variant="h6"
                  style={{
                    fontFamily: 'roboto',
                    color: '#2F4858',
                    marginTop: '1em',
                  }}
                >
                  Mobile Number (Optional)
                </Typography>
                <Field
                  name="number"
                  placeholder="Contact Number"
                  component={MyInput}
                  // label="Contact Number"
                />
                <br />
                {errors.number && touched.number ? (
                  <div className="text-danger" style={{ color: 'red' }}>
                    {errors.number}
                  </div>
                ) : null}
                <Typography
                  variant="h6"
                  style={{
                    fontFamily: 'roboto',
                    color: '#2F4858',
                    marginTop: '1em',
                  }}
                >
                  Company Name (Optional)
                </Typography>
                <Field
                  name="companyname"
                  placeholder="Company Name"
                  // label="Contact Number"
                  component={MyInput}
                />
                <br />
                <Typography
                  variant="h6"
                  style={{
                    fontFamily: 'roboto',
                    color: '#2F4858',
                    marginTop: '1em',
                  }}
                >
                  How can we help? (Optional)
                </Typography>
                <Field
                  id="outlined-multiline-static"
                  name="message"
                  placeholder="Your question about our services"
                  label="How can we help?"
                  component={Textarea}
                />
                <br />
                <br />
                <Button
                  type="submit"
                  variant="contained"

                  style={{
                    background: '#F79924',
                    color: 'white',
                    fontFamily: 'roboto',
                    fontSize: '1rem',
                  }}
                >
                  Submit{' '}
                </Button>
                <br />
                {state.msg && (
                  <Typography
                    variant="h6"
                    style={{
                      color: '#4BB543',
                      fontFamily: 'roboto-medium',
                      marginTop: '1em',
                    }}
                  >
                    {' '}
                    {state.msg}{' '}
                  </Typography>
                )}
              </Form>
            </Grid>
          </Grid>
        )}
      </Formik>
    </div>
  );
}

我想你快到了。 const email = findemail.split('?')[1].split('&')[0] returns abcxyz@gmail.com.

这是您所期待的吗?

注意:上面假设findemail总是在.com/?之后有一封电子邮件。如果它是随机的,那么我不确定你是否能收到电子邮件。我们要么需要标准输入,要么写多个 switch case 语句