javascript - 我不明白 reactJs 中的这个组件渲染行为
问题描述
我有一个登录表单。如果凭证是商品,则会进行重定向,否则会显示通知。我在标题中提到的行为是该Notification
组件似乎在提醒它的“状态”。如果我发表评论This line
,则通知仅呈现一次,如果不是每次我提交我想要的错误凭据时都重新呈现通知。
登录表单 :
const loginForm = () => {
const [login,setLogin] = useState("");
const [password,setPassword] = useState("");
const [loginResult, setLoginResult] = useState(null);
const handleSubmit = async (e) => {
e.preventDefault();
setLoginResult(); // ---> This line <---
const res = await checkApi(login,password);
switch(res){
case 200:
setLoginResult(
<Redirect to="/somewhere" />
);
break;
case 404:
setLoginResult(
<Notification />
); // Each time I submit bad credentials
}
}
return(
<>
{loginResult} //Either <Notification /> or <Redirect />
<Container>
<div>
<form onSubmit={handleSubmit}>
<input type="text" onChange={(e)=>setLogin(e.target.value)} placeholder="username" />
<input type="password" onChange={(e)=>setPassword(e.target.value)} placeholder="password" />
<button buttontype="submit">submit</button>
</form>
</div>
</Container>
</>
);
}
这是通知:
const Notification = ({variant,title,message}) => {
const [show, setShow] = useState(true);
useEffect(() => {
console.log("notification rendered"); // I display this when the notification is rendered
}, [])
if(show){
return (
<Alert variant={variant} onClose={()=>setShow(false)} dismissible>
<Alert.Heading>
{title}
</Alert.Heading>
<p>
{message}
</p>
</Alert>
);
}else{
return(
<>
</>
);
}
}
实际上我的代码符合我的预期,但我想知道它是如何工作的。谢谢 !
解决方案
推荐阅读
- java - 获取 java.io.IOException: Stream closed error without显式关闭它
- python - 为什么“os.path.join”和“os.path.dirname(__file__)”返回不同的分隔符?
- c# - 将泛型类 T 存储在变量中并在子方法中重用它
- apache-spark - 我是否可以加快在 pyspark 上运行 python 库的速度
- css - 将 CSS transition-timing-function 翻译成滑动
- r - R:调用 addHandlerClicked 后向量不会改变(gWidgets)
- php - 与 phpmyadmin 相比,php mysqli 返回不同的行数
- python - python selenium firefox,用于身份验证弹出的特殊字符@
- angular - Sass Angular + 主题
- excel - Excel Powerquery 拆分表格顶部/底部 50%