更新:为什么即使 onClick 执行了功能任务,我的 buttonText 也没有改变它的状态?

Updated: why is my buttonText not changing it's status even the onClick executes the function task?

我的主要目标是制作一个由 node.js 和 reactjs material ui 组成的联系表格。这个项目是一个虚拟项目,我将把它整合到主要项目中。

这是我与 node.js 的第一部作品。我使用 nodemailer 创建了一个 index.js 文件来发送电子邮件。代码如下:

const express = require("express");
const router = express.Router();
const cors = require("cors");
const nodemailer = require("nodemailer");

const app = express();
app.use(cors());
app.use(express.json());
app.use("/", router);
app.listen(5000, () => console.log("Server Running"));

const contactEmail = nodemailer.createTransport({
  service: "gmail",
  auth: {
    user: "*******@gmail.com",
    pass: "********",
  },
});

contactEmail.verify((error) => {
  if (error) {
    console.log(error);
  } else {
    console.log("Ready to Send");
  }
});

router.post("/contact", (req, res)  =>{
  const name = req.body.name;
  const email = req.body.email;
  const message = req.body.message;
  const mail = {
    from: name,
    to: "random_emil@gmail.com",
    subject: "Contact Form Message",
    html: `<p>Name: ${name}</p><p>Email: ${email}</p><p>Message: ${message}</p>`,
  };
contactEmail.sendMail(mail, (error)=>  {
  if(error){
  res.JSON.stringify(error);
  }else{
    res.JSON.stringify({ 'result': " email sent successfully" });
  }
})

})

在执行 node server 时没有显示错误。

在客户端,我用material-ui写了Contact.js:

import React,{useState} from 'react'
import axios from 'axios'
import { Button,FormControl, TextField } from "@material-ui/core";
export default function Contact() {
    const [data, setData] = useState({
      name: "",
      email: "",
      message: "",
      sent: false,
      buttonText: "Submit",
      err: "",
    });

    const handleChange = (e) => {
      const { name, value } = e.target;
      setData({
        ...data,
        [name]: value,
      });
    };
    const formSubmit = (e) => {
        e.preventDefault();

        setData({
            ...data,
            buttonText: 'Sending...'
        })

        axios
          .post("http://localhost:5000/contact", data)
          .then((res) => {
            if (res.data.result !== "email sent successfully") {
              setData({
                ...data,
                buttonText: "Failed to send",
                sent: false,
                err: "fail",
              });
              setTimeout(() => {
                resetForm();
              }, 3000);
            } else {
              setData({
                ...data,
                sent: true,
                buttonText: "Sent",
                err: "success",
              });
              setTimeout(() => {
                resetForm();
              }, 3000);
            }
          })
          .catch((err) => {
            //console.log(err.response.status)
            setData({
              ...data,
              buttonText: "Failed to send",
              err: "fail",
            });
          });
          const resetForm = () => {
            setData({
              name: "",
              email: "",
              message: "",
              sent: false,
              buttonText: "Submit",
              err: "",
            });
          };
    }
    return (
      <React.Fragment>
        <FormControl fullWidth={true}>
          <TextField
            required
            label="Full name"
            variant="filled"
            id="full-name"
            name="name"
            className="form-field"
            value={data.name}
            onChange={handleChange}
          />
        </FormControl>
        <FormControl fullWidth={true}>
          <TextField
            required
            label="Email"
            id="email"
            name="email"
            variant="filled"
            className="form-field"
            value={data.email}
            onChange={handleChange}
          />
        </FormControl>
        
        <FormControl fullWidth={true}>
          <TextField
            required
            label="Message"
            variant="filled"
            name="message"
            multiline={true}
            rows="10"
            value={data.message}
            onChange={handleChange}
          />
        </FormControl>
        <FormControl>
          <div className="form-submit">
            <Button variant="contained" color="primary" onClick={formSubmit}>
              {data.buttonText}
            </Button>
          </div>
        </FormControl>
      </React.Fragment>
    );
}

执行 npm start 后,本地服务器发送表单,当我将数据放入名称、电子邮件和消息字段以提交时,按钮显示正在发送......并且它永远不会结束。但在我的电子邮件中,我发现服务器 js 发送的电子邮件正是我想要的。

如何将我的 {buttonText} 消息更新为提交?我在 formSubmit 函数中做错了什么?

请帮忙

您的服务器代码成功调用了 .sendMail() 方法,这就是电子邮件被送达的原因。但是,您的响应代码不正确。使用 JSON 负载响应的正确 Express 响应方法是 res.json(payload),而不是 res.JSON.stringify(payload)

如果你修复了它,它应该可以工作。