如何在UseEffect渲染页面/组件?



我有下面的代码-

function checkIfSignedIn()
{
axios.get(`https://localhost:44301/api/login/ValidateLogin`)
.then(res=>{ 
console.log(JSON.stringify(res.data));
setLoginCredentials({
...loginCreds,
isLoggedIn:res.data
});
dispatch(StoreUserAuthenticationStatusAction(res.data));
});
}
const iLoginCreds ={
userName:'',
password:'',
isLoggedIn:false
}
const [loginCreds, setLoginCredentials] = useState(iLoginCreds)
useEffect(() => {
alert(loginCreds.isLoggedIn);
return (
<>
<MainPage></MainPage>
</>
)
}, [loginCreds.isLoggedIn])
return (
<>
...
...
...
<FormGroup>
<Button style={{width:'100%',backgroundColor:"#FCB724",color:"black",fontWeight:"bold"}} onClick={checkIfSignedIn}  >Sign in using our secure server</Button>
</FormGroup>
</>
)

总之,我在这里做什么-

单击按钮-通过api检查/验证凭据。Api发送- true/false然后我在setlogincreential中更新我的状态,并在store中调度。在状态改变时触发useEffect——我正在渲染到MainPage(它没有被渲染)

问题是什么?-

在这段代码中,在使用effect触发器时,我想将我的页面呈现给MainPage。通过保持警惕,我已经确保useEffect被适当地触发了。但是我不能看到我的页面被渲染。

您应该在useEffect之外返回JSX,在功能组件的返回中,像这样:

return(
iLoginCreds.isLoggedIn
?(
<>
<MainPage></MainPage>
</>
)
:(
<>
...
...
...
<FormGroup>
<Button style={{width:'100%',backgroundColor:"#FCB724",color:"black",fontWeight:"bold"}} onClick={checkIfSignedIn}  >Sign in using our secure server</Button>
</FormGroup>
</>
)
)

最新更新