首页 > 解决方案 > 如何在 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 被适当地触发。但我看不到我的页面被渲染。

标签: javascriptreactjsredux

解决方案


您应该在 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>
            </>
    )
)

推荐阅读