首页 > 解决方案 > history.push 每次都不起作用

问题描述

我正在制作一个 ReactJS 项目,在登录页面中,我添加了当用户登录成功时,他会自动重定向到网站主页的功能。身份验证是通过 Firebase 进行的,这是代码

auth.signInWithEmailAndPassword(email, password)
       .then(() => {
            console.log('Successfully signed in');
            this.setState({
                isLoading : false
            });
            this.props.history.push('/main');
       })
       .catch(err => {
           alert("There was some error signing in");
           console.log(err);
       })

但是,history.push 并非每次都有效。有时当我登录时,它会重定向到所需的页面,但有时不会。

请告诉发生了什么问题以及如何解决

标签: javascriptreactjsfirebasefirebase-authenticationreact-router

解决方案


我在后端使用 mongodb 时遇到了同样的问题。有时我可以在历史推送后看到更新的值,但有时没有。我通过在调用后端路由的 onSubmit 方法中使用超时值解决了这个问题。

setTimeout(() => {  history.push("/") }, 10);

推荐阅读