我有一个使用React的AWS Amplify应用程序。我希望只有当用户成功登录时才能加载(或重新加载(TaskList
组件。但是,当页面加载时,该组件从一开始就被呈现,当用户填写表单并注册时,它不会重新加载。我一直在尝试多种解决方案,但我不知道如何使我的组件依赖于成功登录。我依靠默认的Amplify验证器功能来让用户登录Cognito。
const App = () => (
<AmplifyAuthenticator>
<div>
My App
<AmplifySignOut />
<TaskList />
</div>
</AmplifyAuthenticator>
);
我使用答案AWS Amplify:onStatusChange中给出的提示解决了这个问题,然后呈现主页。
基本上,我更改了我的应用程序组件,只返回登录表单或基于身份验证状态更改的整个up。
const App = () => {
const [authState, setAuthState] = useState('');
function handleAuthStateChange(state) {
if (state === 'signedin' || state === 'signedout') {
setAuthState(state);
}
}
return (
<div>
{ authState !== 'signedin' ?
<AmplifyAuthenticator>
<AmplifySignIn handleAuthStateChange={handleAuthStateChange} slot="sign-in"></AmplifySignIn>
</AmplifyAuthenticator>
:
<div>
My App
<AmplifySignOut handleAuthStateChange={handleAuthStateChange} slot="sign-out"/>
<TaskList />
</div>
}
</div>
);
}
这就是我解决类似问题以管理状态的方法。我遇到了一些问题,因为它似乎没有在事后发布事件。
发件人https://github.com/aws-amplify/amplify-js/issues/5825
import React from 'react';
import { AmplifyAuthenticator, AmplifySignOut, AmplifySignUp, AmplifySignIn} from '@aws-amplify/ui-react';
import { onAuthUIStateChange } from '@aws-amplify/ui-components'
const Panel = () => {
const [setAuthState] = React.useState();
React.useEffect(() => {
return onAuthUIStateChange(newAuthState => {
if(newAuthState === 'signedin'){
// Do your stuff
}
setAuthState(newAuthState)
});
}, []);
return(
<AmplifyAuthenticator>
<AmplifySignIn headerText="Sign In" slot="sign-in"/>
<AmplifySignUp slot="sign-up" formFields={[
{type: 'username'},
{type: 'email'},
{type: 'password'}
]}></AmplifySignUp>
<AmplifySignOut></AmplifySignOut>
</AmplifyAuthenticator>
)
}
export default Panel;