【问题标题】:ReactJs/NextJS - automatic redirect after 5 seconds to another pageReactJs/NextJS - 5 秒后自动重定向到另一个页面
【发布时间】:2021-11-10 10:26:47
【问题描述】:
  • 我正在创建欢迎页面,该页面应在客户登录后立即出现,并且此页面应在 5 秒后自动将客户重定向到另一个页面。我尝试使用默认值为 5 秒的 setState,然后使用 1000 毫秒的 setInterval,将其减 1,当涉及到 0 时,重定向客户。

Console.log() 总是返回 5,所以基本上在前端我总是看到这句话: 欢迎,您已成功登录,您将被重定向到.. 4

看起来是这样,因为 setRedirectSeconds() 是异步的,所以它不会立即更新状态,每当我的 setInterval 函数再次启动时,redirectSeconds 每次仍然是 5。

如何解决?

这是我的代码:

const Welcome: NextPage = (): ReactElement => {
const [redirectSeconds, setRedirectSeconds] = useState<number>(5);
const router = useRouter();
const query = router.query;

useEffect(() => {
    if (query?.redirect) {
        setTimeout(() => {
            const interval = setInterval(() => {
                console.log(redirectSeconds);
                if (redirectSeconds > 0) {
                    setRedirectSeconds(redirectSeconds - 1);
                } else {
                    clearInterval(interval);
                    router.push(query.redirect.toString());
                }
            }, 1000)
        }, 1000);
    }
}, []);

return (
        <div>
            Welcome, you have successfully logged in, you will be redirected in.. {redirectSeconds}
        </div>
);
};

export default Welcome;

【问题讨论】:

  • 我发现这篇很棒的文章 thewebdev.info/2021/02/03/… 更新了我的状态并每秒减少 1 并在前端显示它,但问题是控制台仍然总是记录 5 并且不会发生重定向

标签: reactjs next.js


【解决方案1】:

这是我调整它的方法,现在它工作正常:

  • 我删除了 setInterval 并添加了对 useEffect 函数的依赖。而且我在减少redirectSeconds之前添加了1000ms的超时时间。

     useEffect(() => {
     if (query?.redirect) {
         if (redirectSeconds == 0) {
             router.push(query.redirect.toString());
             return;
         }
    
         setTimeout(() => {
             console.log(redirectSeconds);
             setRedirectSeconds((redirectSeconds) => redirectSeconds - 1);
         }, 1000)
     }
    }, [redirectSeconds]);
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-02
    • 2019-03-31
    • 1970-01-01
    • 2014-09-02
    • 2012-08-11
    • 1970-01-01
    • 2015-03-09
    • 2019-11-21
    相关资源
    最近更新 更多