我试图在React的功能组件中实现简单的更新,但似乎偶然发现了一些基本的逻辑错误。你能帮忙吗?
我的代码:
import React, { useState } from "react";
import "./App.css";
var timeout; // this variable wasn't scoped inside the function?.
function App() {
const [name, setUserName] = useState("");
const [password, setUserPassword] = useState("");
const [showHackMessage, setShowHackMessage] = useState(false);
const enterUserName = e => {
console.log(e.target.value);
setUserName(e.target.value);
};
const enterUserPassword = (e) => {
console.log(e.target.value,timeout);
setUserPassword(e.target.value);
if (e.target.value.length > 0) {
timeout= setTimeout(()=>setShowHackMessage(true), 1000);
console.log(timeout);
/// Why did not timeout= setTimeout(setShowHackMessage(true), 5000); work? is setShowHackMessage not a function?
// timeout();
}
else if(e.target.value.length===0) {
console.log("Tricky user!");
console.log(timeout,'L29>>');
//not working perfectly!
clearTimeout(timeout);
setShowHackMessage(false);
}
};
return (
<div className="App">
<p>Login-Hacker</p>
<input name={"email"} onChange={enterUserName}></input>
<br></br>
<br></br>
<input name={"password"} onChange={(e)=>enterUserPassword(e)}></input>
<p>Powered by Saurabh</p>
{name.length > 0 && <p>Your name is {name}</p>}
{password.length > 0 && <p>Your password is {password}</p>}
{showHackMessage && <p className='awesome'>Now you are hacked!</p>}
</div>
);
}
export default App;
所以我的第一个问题是:-
为什么在settimeout中定义setstate函数时必须使用回调? 我尝试过
timeout = setTimeout(setShowHackMessage(true),1000);
timeout = setTimeout(()=> setShowHackMessage(true),1000); 完美地工作。 setShowHackMessage(在useState中不是函数吗?)
如果我在函数内部定义变量var timeout,则cleartimeout不起作用(在控制台中显示为undefined),但是如果我在函数外部(如代码中)对其进行定义,则cleartimeout可以完美地工作。整个函数是否在setstate之后“呈现”(因此丢失了变量超时的先前实例?)。我应该为此使用引用吗?
谢谢。