设置一个在React中反映函数是否已完成运行的状态?

huangapple go评论78阅读模式
英文:

How to set a state in react that reflects if a function has completed running or not?

问题

我有一个需要很长时间才能运行的函数,并且需要在React中实现一种"加载"消息,该消息在函数启动时显示,并在完成后消失。

我的第一个想法是类似于以下内容:

const myComponent = () => {

    const [isLoadingState, setIsLoadingState] = useState(false)

    // 当某些状态更新时触发此函数
    function verySlowFunction() {
        setIsLoadingState(true);
        // 各种需要很长时间的函数调用在这里
        setIsLoadingState(false);
    }

    return (
        <h1>我们的组件在这里</h1>
        {isLoadingState ? <h5>当前正在加载...</h5> : ''}
    )
}

想法是,当函数开始时,'isLoadingState' 变为 'true',因此在底部返回的组件将显示为"当前正在加载...",当它到达函数的最后一行时,将其设置回 'false',以便 h5 组件消失。 (逻辑已经经过测试,按预期工作)。

我使用这种方法遇到的问题是,由于某种原因, setIsLoadingState 似乎没有在初始加载后设置组件为 true 或 false。

是否有人有任何想法,我可能做错了什么,或者有更好的建议,我可以以这种方式进行操作(而无需更改 "verySlowFunction()" 的实现)?

英文:

I have a function which takes a long time to run, and need to implement a type of 'loading' message in React which displays when the function starts and goes away once it finishes.

My first idea was something along the lines of,

const myComponent = () =&gt; {

    const [isLoadingState, setIsLoadingState] = useState(false)

    // This function gets triggered whenever certain states get updated
    function verySlowFunction(): {
        setIsLoadingState(true);
        // various function calls
        // which take a long amount of time
        // here
        setIsLoadingState(false);
    }

    return (
        &lt;h1&gt;Our component here&lt;/h1&gt;
        {isFetchingState ? &lt;h5&gt;Currently loading...&lt;/h5&gt; : &#39;&#39;}
    )
}

The idea being, when the function starts, 'isLoadingState' becomes 'true', and thus the component being returned at the bottom will show as "Currently loading...", and when it gets to the last line of the function, it sets it back to 'false', so that h5 component goes away. (The logic has been tested and works as-expected there).

The problem I run into with this approach is that, for whatever reason, setIsloadingState doesn't appear to be setting the component to true or false after the initial load.

Does anyone have any ideas what I might be doing wrong, or suggestions on better ways I could be doing this (without having to change the implementation of "verySlowFunction()"?

答案1

得分: 1

你可以使用Promise来处理这种情况。

function SamplePromise() {
  var promise = new Promise(function(resolve, reject) {
    //做一些事情
    resolve('你的结果')
  });
  return promise; 
}

然后你可以调用这个函数,使用then来获取你的数据并改变加载状态,例如:

await SamplePromise().then((data) => setIsLoadingState(false))

then()将在你的Promise完成工作后被调用。

英文:

You can use a promise to handle this situation.

function SamplePromise() {
 var promise = new 
   Promise(function(resolve, reject) {
  //Do something 
 resolve(&#39;your result&#39;)
 });
 return promise; 

Then you can call this function and use then to get your data and change the loading state. Such as

await SamplePromise().then((data)=&gt; 
 setIsLoadingState(false))

.then() will be called when your promise finishes doing the work.

答案2

得分: 1

React 18引入了新的钩子。

useTransition是一个React Hook,允许您在不阻塞用户界面的情况下更新状态。

您可以像下面这样使用:

function App() {
  const [isPending, startTransition] = useTransition();
  const verySlowFunction = () => {...};

  useEffect(() => {
    startTransition(() => {
      verySlowFunction();
    });
  }, [])

  return (
    <>
      <h1>我们的组件在这里</h1>
      {isPending ? <h5>正在加载中...</h5> : ""}
    </>
  );
}
英文:

React 18 introduce new hook.

useTransition is a React Hook that lets you update the state without blocking the UI.

You can do like below:

function App() {
  const [isPending, startTransition] = useTransition();
  const verySlowFunction = () =&gt; {...};

  useEffect(() =&gt; {
    startTransition(() =&gt; {
      verySlowFunction();
    });
  }, [])

  return (
    &lt;&gt;
      &lt;h1&gt;Our component here&lt;/h1&gt;
      {isPending ? &lt;h5&gt;Currently loading...&lt;/h5&gt; : &quot;&quot;}
    &lt;/&gt;
  );

}

huangapple
  • 本文由 发表于 2023年6月29日 05:20:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576778.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定