[英]React useState changing value but not rerendering?
我正在嘗試為我的 AWS Authenticator 組件創建自定義重定向,其中重定向 URL 將根據用戶是注冊還是登錄而有所不同:
export default function Login() {
const { route } = useAuthenticator(context => [context.route]);
const [redirectURL, setRedirectURL] = useState(getHomePath());
if (route === "signIn" && redirectURL !== getHomePath()) {
setRedirectURL(getHomePath());
} else if (route === "signUp" && redirectURL !== getCreateProfilePath()) {
setRedirectURL(getCreateProfilePath());
}
console.log(redirectURL);
return route === "authenticated" ? (
<Navigate to={redirectURL} />
) : (
<Authenticator
// Default to Sign Up screen
initialState="signUp"
// Customize `Authenticator.SignUp.FormFields`
signUpAttributes={["birthdate"]}
formFields={formFields}
components={components}
services={{
async validateCustomSignUp(formData) {
if (!formData.acknowledgement) {
return {
acknowledgement: redirectURL
};
}
}
}}
/>
);
}
為此,我使用狀態掛鈎設置重定向 URL,該狀態掛鈎取決於用戶選擇“signIn”還是“signUp”。 這似乎有效,正如我在控制台中看到的那樣, redirectURL
在選擇時會發生變化。 但是,似乎組件本身沒有重新渲染(盡管值發生了變化); redirectURL
不會傳播到return
語句,並且Authenticator
保持默認值並且不會更改。
是否有一個原因?
請查看此解決方案是否能解決您的問題
export default function Login() {
const { route } = useAuthenticator(context => [context.route]);
const [redirectURL, setRedirectURL] = useState(getHomePath());
useEffect(() => {
if (route === "signIn" && redirectURL !== getHomePath()) {
setRedirectURL(getHomePath());
} else if (route === "signUp" && redirectURL !== getCreateProfilePath()) {
setRedirectURL(getCreateProfilePath());
}
}, [route])
console.log(redirectURL);
return route === "authenticated" ? (
<Navigate to={redirectURL} />
) : (
<Authenticator
// Default to Sign Up screen
initialState="signUp"
// Customize `Authenticator.SignUp.FormFields`
signUpAttributes={["birthdate"]}
formFields={formFields}
components={components}
services={{
async validateCustomSignUp(formData) {
if (!formData.acknowledgement) {
return {
acknowledgement: redirectURL
};
}
}
}}
/>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.