javascript - 如何在 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 然后我在 setLoginCredentials 中更新我的状态并在商店中调度。在状态更改时触发 useEffect - 我正在渲染到 MainPage(未渲染)
什么是问题?-
在这段代码中,在 useEffect 触发时,我想将我的页面呈现到 MainPage。通过保持 alert ,我确保 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>
</>
)
)
推荐阅读
- json - 在 Postman 的数组中选择第二个对象
- angular - 根据角度中的日期列值更改剑道网格中的行颜色
- reactjs - 如何在反应中点击重新渲染组件
- javascript - 通过传递选项 JSON 使用 Mongoose 过滤数据数据库级别
- ruby-on-rails - 从嵌套的 Rails 中选择属性包括与 ActiveModelSerializer 的关联?
- r - plm() 与 lm() 具有多个固定效果
- python - 递归打印当前目录中文件的脚本
- javascript - 无法使用 JS 切换侧边栏
- javascript - 如何停止 Internet Explorer 10 中 mouseover/mouseout 事件的事件冒泡?
- reactjs - 如何使用从 Express 路由到 React Router 路由的数据