我是否需要一个异步函数来正确包含一个工作的预加载器组件?

问题描述 投票:0回答:1

我正在使用一个Electron React应用程序,我很好奇是否需要一个异步函数来正确显示预加载器svg。svg是存储在状态中的,当我通过显示它而不删除它来测试它时,它工作得非常好。然而,当我真正尝试在我的应用程序的过程中使用它时,它似乎从未显示出来。

以下是我想要的样子 (我通过注释出处理文件后将状态改回null的地方来实现)

我得到的是这样的结果 (当我把状态从装载机改回null的时候会发生什么......没有看到装载机!)

我的问题是,这是我需要一个异步函数来实现的吗?我对正确使用async await并不是非常熟悉,而且这也不是我第一次在react应用中遇到这个问题。我只是一般地想弄清楚为什么当我按照预期的方式实现时,加载器似乎从未出现过。老实说,我可能只是在这里犯了一个新手错误,所以我希望得到第二种意见!

在App.js中。

const [loading, setLoading] = useState(null);

const handleLoading = (value) => {
    setLoading(value);
};

...

<Route exact path="/list">
    <List loading={loading} />
</Route>
<Route exact path="/">
    <Start loading={handleLoading} />
</Route>

在Start. js里

const handleFiles = (files) => {
            // *set the loading state to the component
            props.loading(
                <div className="base-loader">
                    <div className="preloader-wrapper big active">
                        <div className="spinner-layer spinner-blue-only">
                            <div className="circle-clipper left">
                                <div className="circle"></div>
                            </div>
                            <div className="gap-patch">
                                <div className="circle"></div>
                            </div>
                            <div className="circle-clipper right">
                                <div className="circle"></div>
                            </div>
                        </div>
                    </div>
                </div>
            );
            // counter to list with a Materialize toast when finished if > 0
            sendFiles(files);
            if (incompatibleFiles > 0) {
                M.toast({
                    html: `${incompatibleFiles} file(s) could not be minified due to incompatible file type.`,
                });
            }
            // reset for next drag and drop
            incompatibleFiles = 0;

            // *THIS is the line I comment out for it to start working (although it just goes infinitely)
            props.loading(null);
        };

最后,在List.js中,我只是简单地加入了以下内容 {props.loading} 的组件返回语句中。

reactjs asynchronous state preloader
1个回答
0
投票

很可能是因为加载是即时的,加载器出现的时间不够长,所以没有注意到。如果你试着在设置超时之前设置一个 loading 国到 false 装载器应该是很明显的。

setTimeout(() => {
  setLoading(false);
}, 500);

然而,我认为,如果加载行为发生得足够快,就没有必要伪造它。最好的做法可能是在500ms-1000ms或其他什么之后开始显示加载器,当普通人类用户开始觉得你的应用程序没有响应,如果没有变化的话。

let timeout = setTimeout(() => {
  if (!dataHasLoaded) {
    setLoading(true);
  } else {
    clearTimeout(timeout);
  }
}, 500);
© www.soinside.com 2019 - 2024. All rights reserved.