简体   繁体   English

使用 reactjs 对 html dom 中的元素进行条件渲染时,输入字段值不会改变

[英]Input field value does not changes on conditional rendering of elements in html dom using reactjs

I'm trying to get an email id, validate it and post it to the server.我正在尝试获取 email id,对其进行验证并将其发布到服务器。 If the email id exists then the respective account's password can be changed.如果 email id 存在,则可以更改相应帐户的密码。 I used a flag to return the jsx.我使用了一个标志来返回 jsx。

if (isEmail in server ) return ( jsx code that has fields to get password (has two input fields)) if(服务器中的isEmail)返回(具有获取密码字段的jsx代码(有两个输入字段))

else return ( jsx code that has fields to get email (has one input field)否则返回(具有字段的jsx代码获取email(有一个输入字段)

Code:代码:

const ForgotPassword = () => {
  const history = useHistory();

  const [Email, setEmail] = useState({
    Email: "",
    isEmail: false,
    isEmailValidate: false,
    Email_msg: ""
  });

  const [Newpassword, setNewpassword] = useState({
    password: "",
    ispassword: false,
    password_msg: ""
  });
  const [NewConfirmpassword, setNewConfirmpassword] = useState({
    confirmpassword: "",
    isconfirmpassword: false,
    confirmpassword_msg: ""
  });

  const validateUserDetails = (value, field) => {
    console.log("value:", value, "field :", field);

    if (field === "Email") {
      if (value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i)) {
        setEmail({
          ...Email,
          Email: value,
          isEmailValidate: true,
          Email_msg: ""
        });
        console.log("matched", Email);
      } else
        setEmail({
          ...Email,
          isEmail: false,
          Email_msg: "Enter a valid Email id"
        });
    }

    if (field === "Enter New Password") {
      if (value.match(/^([\w]{6,})/)) {
        setNewpassword({
          ...Newpassword,
          password: value,
          ispassword: true,
          password_msg: ""
        });
      } else {
        setNewpassword({
          ...Newpassword,
          password: value,
          ispassword: false,
          password_msg: "Enter a password greater than 6 characters"
        });
      }
    }

    if (field === "Confirm Password") {
      console.log(value, Newpassword.password, "Passwords");
      if (value === Newpassword.password) {
        // console.log("password matched")
        setNewConfirmpassword({
          ...NewConfirmpassword,
          confirmpassword: value,
          isconfirmpassword: true,
          confirmpassword_msg: ""
        });
      } else {
        setNewConfirmpassword({
          ...NewConfirmpassword,
          confirmpassword_msg: "Enter the password same as above",
          isconfirmpassword: false
        });
      }
    }
  };

  const EmailCheckCall = () => {
    let obj = {};
    obj.email = Email.Email;

    (async () => {
      const rawResponse = await fetch(
        "http://127.0.0.1:8000/api/account/accountcheck",
        {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: JSON.stringify(obj)
        }
      );
      const content = await rawResponse.json();
      console.log(content);
      if (content.response === "Account Exists") {
        // history.push('/home/login')
        console.log("Setting isemail true");
        setEmail({
          ...Email,
          isEmail: true
        });
      }
    })();
  };

  const PasswordChangeCall = () => {
    let obj = {};
    obj.email = Email.Email;
    obj.password = NewConfirmpassword.confirmpassword;

    (async () => {
      const rawResponse = await fetch(
        "http://127.0.0.1:8000/api/account/forgotpassword",
        {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: JSON.stringify(obj)
        }
      );
      const content = await rawResponse.json();
      // console.log(content);
      if (content.response === "Password Changed") {
        alert("Password Changed Please Login");
        history.push("/home/login");
        // console.log("Password Changed")
      } else {
        setEmail({
          ...Email,
          Email: "",
          isEmail: false
          // isEmailValidate: false,
        });
      }
    })();
  };

  const Onsubmitclick = event => {
    event.preventDefault();
    if (event.target.id === "Next") {
      console.log("place holder : ", event.target.id);
      if (Email.isEmailValidate) {
        console.log("Inside Onsubmit :", Email);
        EmailCheckCall();
      }
    }

    if (event.target.id === "Back") {
      setEmail({
        ...Email,
        Email: "",
        isEmail: false
        // isEmailValidate: false,
      });
    }

    // Send the user details to backend
    if (event.target.id === "submitpassword") {
      PasswordChangeCall();
    }
    console.log(Email, "Email");
    // Send the user details to backend
  };

  if (Email.isEmail)
    return (
      <div className="fpassOuterContainer">
        <h1 className="fpassHeader"> Enter New Password </h1>{" "}
        <form className="fpassFormContainer">
          <input
            className="fpassInput mt-20"
            type="text"
            placeholder="Enter New Password"
            onChange={event =>
              validateUserDetails(event.target.value, event.target.placeholder)
            }
          />{" "}
          <p> {Newpassword.password_msg} </p>
          <input
            className="fpassInput mt-20"
            type="text"
            placeholder="Confirm Password"
            onChange={event =>
              validateUserDetails(event.target.value, event.target.placeholder)
            }
          />{" "}
          <p> {NewConfirmpassword.Confirmpassword_msg} </p>
          <button
            id="Back"
            onClick={event => Onsubmitclick(event)}
            className="fpassBtn-login mt-20 ms-25"
          >
            {" "}
            Back{" "}
          </button>
          <button
            id="submitpassword"
            onClick={event => Onsubmitclick(event)}
            className="fpassBtn-login mt-20 ms-25"
          >
            {" "}
            Submit{" "}
          </button>
        </form>{" "}
      </div>
    );
  else
    return (
      <div className="fpassOuterContainer">
        <h1 className="fpassHeader"> Forgot Password </h1>{" "}
        <form className="fpassFormContainer">
          <input
            className="fpassInput mt-20"
            type="text"
            placeholder="Email"
            onChange={event =>
              validateUserDetails(event.target.value, event.target.placeholder)
            }
          />{" "}
          <p> {Email.Email_msg} </p>
          <button
            id="Next"
            onClick={event => Onsubmitclick(event)}
            className="fpassBtn-login mt-20 ms-25"
          >
            {" "}
            Next{" "}
          </button>
        </form>{" "}
      </div>
    );
};

export default ForgotPassword;

Here the email is typed and next is pressed这里输入 email 然后按下下一个

After next is pressed on the email entering screen, the password page is rendered, In that first input field is for entering new password and second is for confirm password, But first input field is already filled with the email id that i have entered in previous screen在email输入界面上按next后,出现密码页面,第一个输入框是输入新密码,第二个输入框是确认密码,但是第一个输入框已经填满了我之前输入的email id屏幕

Please look into the images so that problem can be understood better请查看图片以便更好地理解问题

How come the input provided in the first screen is still present in the second screen?为什么第一个屏幕中提供的输入仍然出现在第二个屏幕中?

How can I clear the input field?如何清除输入字段?

autocomplete='off自动完成='关闭

I appreciate any help我很感激任何帮助

Work it out in this way以这种方式解决

import React, { useState } from "react";

const ForgotPassword = () => {
  // const history = useHistory();

  const [Email, setEmail] = useState({
    Email: "",
    isEmail: false,
    isEmailValidate: false,
    Email_msg: ""
  });

  const [Newpassword, setNewpassword] = useState({
    password: "",
    ispassword: false,
    password_msg: ""
  });
  const [NewConfirmpassword, setNewConfirmpassword] = useState({
    confirmpassword: "",
    isconfirmpassword: false,
    confirmpassword_msg: ""
  });

  const validateUserDetails = (value, field) => {
    if (field === "Email") {
      if (value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2,})$/i)) {
        setEmail({
          ...Email,
          Email: value,
          isEmailValidate: true,
          Email_msg: ""
        });
        console.log("matched", Email);
      } else
        setEmail({
          ...Email,
          Email: value,
          isEmail: false,
          Email_msg: "Enter a valid Email id"
        });
    }

    if (field === "Enter New Password") {
      if (value.match(/^([\w]{6,})/)) {
        setNewpassword({
          ...Newpassword,
          password: value,
          ispassword: true,
          password_msg: ""
        });
      } else {
        setNewpassword({
          ...Newpassword,
          password: value,
          ispassword: false,
          password_msg: "Enter a password greater than 6 characters"
        });
      }
    }

    if (field === "Confirm Password") {
      console.log(value, Newpassword.password, "Passwords");
      if (value === Newpassword.password) {
        // console.log("password matched")
        setNewConfirmpassword({
          ...NewConfirmpassword,
          confirmpassword: value,
          isconfirmpassword: true,
          confirmpassword_msg: ""
        });
      } else {
        setNewConfirmpassword({
          ...NewConfirmpassword,
          confirmpassword_msg: "Enter the password same as above",
          isconfirmpassword: false
        });
      }
    }
  };

  const EmailCheckCall = () => {
    setEmail({
      ...Email,
      isEmail: true
    });
    // let obj = {};
    // obj.email = Email.Email;

    // (async () => {
    //   const rawResponse = await fetch(
    //     "http://127.0.0.1:8000/api/account/accountcheck",
    //     {
    //       method: "POST",
    //       headers: {
    //         Accept: "application/json",
    //         "Content-Type": "application/json"
    //       },
    //       body: JSON.stringify(obj)
    //     }
    //   );
    //   const content = await rawResponse.json();
    //   console.log(content);
    //   if (content.response === "Account Exists") {
    //     // history.push('/home/login')
    //     console.log("Setting isemail true");
    //     setEmail({
    //       ...Email,
    //       isEmail: true
    //     });
    //   }
    // })();
  };

  const PasswordChangeCall = () => {
    let obj = {};
    obj.email = Email.Email;
    obj.password = NewConfirmpassword.confirmpassword;

    (async () => {
      const rawResponse = await fetch(
        "http://127.0.0.1:8000/api/account/forgotpassword",
        {
          method: "POST",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
          },
          body: JSON.stringify(obj)
        }
      );
      const content = await rawResponse.json();
      // console.log(content);
      if (content.response === "Password Changed") {
        alert("Password Changed Please Login");
        // history.push("/home/login");
        // console.log("Password Changed")
      } else {
        setEmail({
          ...Email,
          Email: "",
          isEmail: false
          // isEmailValidate: false,
        });
      }
    })();
  };

  const Onsubmitclick = event => {
    event.preventDefault();
    if (event.target.id === "Next") {
      if (Email.isEmailValidate) {
        console.log("Inside Onsubmit :", Email);
        EmailCheckCall();
      }
    }

    if (event.target.id === "Back") {
      setEmail({
        ...Email,
        Email: "",
        isEmail: false
        // isEmailValidate: false,
      });
    }

    // Send the user details to backend
    if (event.target.id === "submitpassword") {
      PasswordChangeCall();
    }
    console.log(Email, "Email");
    // Send the user details to backend
  };

  if (Email.isEmail)
    return (
      <div className="fpassOuterContainer">
        <h1 className="fpassHeader"> Enter New Password </h1>{" "}
        <form className="fpassFormContainer">
          <input
            className="fpassInput mt-20"
            type="text"
            value={Newpassword.password}
            placeholder="Enter New Password"
            onChange={event =>
              validateUserDetails(event.target.value, event.target.placeholder)
            }
          />{" "}
          <p> {Newpassword.password_msg} </p>
          <input
            className="fpassInput mt-20"
            type="text"
            placeholder="Confirm Password"
            onChange={event =>
              validateUserDetails(event.target.value, event.target.placeholder)
            }
          />{" "}
          <p> {NewConfirmpassword.Confirmpassword_msg} </p>
          <button
            id="Back"
            onClick={event => Onsubmitclick(event)}
            className="fpassBtn-login mt-20 ms-25"
          >
            {" "}
            Back{" "}
          </button>
          <button
            id="submitpassword"
            onClick={event => Onsubmitclick(event)}
            className="fpassBtn-login mt-20 ms-25"
          >
            {" "}
            Submit{" "}
          </button>
        </form>{" "}
      </div>
    );
  else
    return (
      <div className="fpassOuterContainer">
        <h1 className="fpassHeader"> Forgot Password </h1>{" "}
        <form className="fpassFormContainer">
          <input
            className="fpassInput mt-20"
            type="text"
            placeholder="Email"
            value={Email.Email}
            onChange={event => {
              validateUserDetails(event.target.value, event.target.placeholder);
            }}
          />{" "}
          <p> {Email.Email_msg} </p>
          <button
            id="Next"
            onClick={event => Onsubmitclick(event)}
            className="fpassBtn-login mt-20 ms-25"
          >
            {" "}
            Next{" "}
          </button>
        </form>{" "}
      </div>
    );
};

export default ForgotPassword;

There are still breakpoints in your application where you need to reset the isEmailValidate key when you press back button.您的应用程序中仍有断点,您需要在按下返回按钮时重置 isEmailValidate 键。 I've commented some of the code which involves mostly the axios request and set the state so that I cound make a demo working to resolve your issue.我评论了一些主要涉及 axios 请求的代码并设置了 state 以便我可以制作一个演示来解决您的问题。

Also I'd recommend you you to separate the logic in two different component and handle it with two different route.另外,我建议您将逻辑分离到两个不同的组件中,并使用两条不同的路线处理它。 Use react-router-dom to handle the routing part and react-hook-form to handle the form event.使用 react-router-dom 处理路由部分,使用 react-hook-form 处理表单事件。

Here is the working demo of your aplication:这是您的应用程序的工作演示:

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM