简体   繁体   中英

Is this a React anti-pattern?

I setState to cause a loading spinner to appear and then call a long running operation. The operation blocks the UI, so the spinner doesn't appear. My workaround is to delay the operation by 500ms with setTimeout, so the spinner has time to appear.

Is there a better way?

It's pretty suspicious for there to be a task that's expensive enough to reliably block rendering on the client. Sometimes a case can be made for it, but in most circumstances there are better approaches.

Ideally, these sorts of expensive operations would be offloaded to your server instead, if at all possible. Instead of the client doing it themselves, have the client make a request to the server, have the server perform the work, and then send the result back to the client. (If you can easily notice a delay on the computer you use for development, someone opening the website on even worse hardware - such as a phone - would have a much worse experience.)

If the above isn't possible, the other main possibility to consider would be to spawn a separate environment on the client, and perform the work in that environment - which will not interfere with rendering (such as the display of a loading spinner) on the original webpage. This can be accomplished with a web worker. . Make a request to the worker while creating the loading spinner, and then the spinner will appear immediately (and animate) while waiting for the worker to finish its processing. Then, have the worker send a message back to the parent page containing the required data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM