【问题标题】:Warning: Cannot update a component (`BrowserRouter`) while rendering a different component (`FormSocialIcon`)警告:在渲染不同的组件(`FormSocialIcon`)时无法更新组件(`BrowserRouter`)
【发布时间】:2022-09-24 04:31:28
【问题描述】:

我在登录时收到警告 [无法更新组件 (BrowserRouter),同时呈现不同的组件 (FormSocialIcon)。]。如何解决此警告?

FormSocialIcon 组件

const FormSocialIcon = () => {
const [signInWithGoogle, user, loading, error] = useSignInWithGoogle(auth);

const navigate = useNavigate();
let location = useLocation();

let from = location.state?.from?.pathname || \"/\";

let errorMessage;
if (error) {
    errorMessage =
        <div>
            <p className=\'text-red-500 font-bold\'>Error: {error.message}</p>
        </div>
}
if (loading) {
    return <Loader></Loader>
}

if (user) {
    navigate(from, { replace: true });
}

return (
    <div>
        <div className=\'flex justify-center items-center mt-3\'>
            <div className=\'bg-indigo-600 w-60 h-0.5\'></div>
            <div className=\'mx-2 font-semibold\'>Or</div>
            <div className=\'bg-indigo-600 w-60 h-0.5\'></div>
        </div>
        <div>
            {errorMessage}
            <button onClick={() => signInWithGoogle()} className=\'w-full md:w-96 flex justify-center mt-5 mx-auto p-2 border-2 border-indigo-500 rounded font-semibold outline-none hover:font-bold hover:transition-all hover:scale-110\'>Continue with google<img className=\'w-5 ml-2\' src={googleIcon} alt=\"\" /></button>
        </div>
    </div>
);

};

标签: javascript node.js reactjs firebase react-router


【解决方案1】:

所以我一直在努力解决同样的问题,我认为它可以使用“useEffect()”钩子来解决。它最终会看起来像这样。

// Replace this:
if (user) {
    navigate(from, { replace: true });
}
// With this
useEffect(()=>{
if (user) {
    navigate(from, { replace: true });
}
},[navigate,user])

可能有更好的方法可以做到这一点,但这对我有用。

【讨论】:

    猜你喜欢
    • 2021-07-05
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2021-03-29
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多