首页 > 解决方案 > 如何在加载器中使用 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

标签: javascriptreactjsreact-functional-componentuse-state

解决方案


您可以添加useEffect挂钩来更新 DOM。

您只是在更新loading处理程序中的标志。React 不知道它需要更新 DOM。

useEffect(() => {
  if (loading) {
    setTimeout(() => {
    setLoading(false);
  }, 2000);
  }
}, [loading]);

分叉的代码框: https ://codesandbox.io/s/inspiring-liskov-t53fv


推荐阅读