I was trying to add login feature through prompt inside react. But I was asked twice the same details by browser. What should I do?

huangapple go评论130阅读模式
英文:

I was trying to add login feature through prompt inside react. But I was asked twice the same details by browser. What should I do?

问题

I was trying to implement login feature in the webpage such that when user give valid credentials then only render the content.
But Browser ask the same credentials twice. But why I have expected that it should ask only once?

Help me to fix this bug?

英文:

I was trying to add login feature through prompt inside react. But I was asked twice the same details by browser. What should I do?

I was trying to implement login feature in the webpage such that when user give valid credentials then only render the content.
But Browser ask the same credentials twice. But why I have expected that it should ask only once?

Help me to fix this bug?

答案1

得分: 0

以下是翻译的代码部分:

import { useState } from "react";

export default function App() {
  const [userId, setUserId] = useState("");
  const [password, setPassword] = useState("");

  const handleLogin = () => {
    setUserId(prompt("Enter your user id:"));
    setPassword(prompt("Enter your password:"));
  };

  if (userId !== "abcd" || password !== "1234") {
    return (
      <>
        <h1>Unauthorized</h1>
        <button type="button" onClick={handleLogin}>
          Login
        </button>
      </>
    );
  }

  return (
    <div className="App">
      <h1>Login successful</h1>
    </div>
  );
}

希望这对你有帮助。

英文:

You can store your variables in a state and implement a simple login page like this:

import { useState } from &quot;react&quot;;

export default function App() {
  const [userId, setUserId] = useState(&quot;&quot;);
  const [password, setPassword] = useState(&quot;&quot;);

  const handleLogin = () =&gt; {
    setUserId(prompt(&quot;Enter your user id:&quot;));
    setPassword(prompt(&quot;Enter your password:&quot;));
  };

  if (userId !== &quot;abcd&quot; || password !== &quot;1234&quot;) {
    return (
      &lt;&gt;
        &lt;h1&gt;Unauthorized&lt;/h1&gt;
        &lt;button type=&quot;button&quot; onClick={handleLogin}&gt;
          Login
        &lt;/button&gt;
      &lt;/&gt;
    );
  }

  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;h1&gt;Login successful&lt;/h1&gt;
    &lt;/div&gt;
  );
}

Link to sandbox.

Using a useEffect will trigger the prompt twice during development unless you disable strict mode.

Link to sandbox with useEffect.

huangapple
  • 本文由 发表于 2023年2月6日 16:10:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75358761.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定