英文:
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 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 "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>
);
}
Link to sandbox.
Using a useEffect
will trigger the prompt twice during development unless you disable strict mode.
Link to sandbox with useEffect
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论