0

我有一个简单的功能组件,我单击一个按钮并显示它,我试图让我的导入微调器在单击按钮时显示 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

4

2 回答 2

2

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

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

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

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

于 2020-03-28T17:29:48.133 回答
0

当您触发helloHandeler()它时,它setTimeout()只会在两秒钟后注册启动!这是 的行为setTimeout()

相反,您应该setLoading()立即,然后setTimeout在 2 秒后停止加载。也许你也想setShow()在两秒之后,所以把它放在setTimeout().

更新

另外,请记住 JS 是异步工作的,因此,当您注册 setTimeout 时,loadingtrue没有。

  const helloHandeler = () => {
    setLoading(true)
    setTimeout(() => {
    setLoading(false)
    setShow(!show);
    }, 2000)

  };
于 2020-03-28T17:18:38.943 回答