首页 > 解决方案 > 我不明白 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(
            <>
            </>
        );
    }
}

实际上我的代码符合我的预期,但我想知道它是如何工作的。谢谢 !

标签: javascriptreactjs

解决方案


推荐阅读