javascript - 如何在加载器中使用 setTimeout
问题描述
我有一个简单的功能组件,我单击一个按钮并显示它,我试图让我的导入微调器在单击按钮时显示 2 秒,然后在两秒后显示我的导入组件,但是我只能让微调器在单击按钮后显示 2 秒并且无法停止
import React, { useState } from "react";
import Hello from "./Hello";
import Spinner from '../Spinner/Spinner'
import "./styles.css";
export default function App() {
const [show, setShow] = useState(false);
const [loading, setLoading] = useState(false);
const helloHandeler = () => {
setTimeout(() => {
setLoading(!loading)
}, 2000)
setShow(!show);
};
if (loading) return <Spinner />
return (
<div className="App">
<h1>Adding a Spinner</h1>
<div className="bodyContainer">
{!show && <button onClick={helloHandeler}>Click me</button>}
{show && <Hello />}
</div>
</div>
);
}
工作示例可以在这里找到:https ://codesandbox.io/s/gallant-engelbart-y3jus
解决方案
您可以添加useEffect
挂钩来更新 DOM。
您只是在更新loading
处理程序中的标志。React 不知道它需要更新 DOM。
useEffect(() => {
if (loading) {
setTimeout(() => {
setLoading(false);
}, 2000);
}
}, [loading]);
分叉的代码框: https ://codesandbox.io/s/inspiring-liskov-t53fv
推荐阅读
- javascript - 静态变量在打字稿中被初始化为未定义
- node.js - 为什么我的后端返回未定义的 req.body?
- selenium - Python Selenium - 无法单击具有 HTML 标记 i 类的 UI 元素
- python - 无法从 Pytorch-Lightning 中的检查点加载模型
- javascript - 在具有子列表的元素列表中搜索/过滤
- typescript - Vue:mixin 调用要在组件中实现的方法是一种反模式吗?
- java - 使用 Azure Java SDK 获取 Authorization_RequestDenied 异常
- button - Xamarin Forms:如何为网格内的单击按钮添加背景颜色(单词搜索游戏)
- c++ - C++ 条件 For 循环,独立计数器
- path - 带有 Handlebar 模板和 nodemailer 的 Firebase 云功能抛出找不到模板的路径