我在 Javascript 中有一个长期运行的任务。React 应该在任务之间的几个点重新渲染组件。但它仅在整个任务结束时重新渲染。如何让 React 在所有setState()调用中重新渲染页面?一个简化的例子:setStatePromise = (state) => new Promise(resolve => { this.setState(state, () => resolve());});longRunningTask = async () => { await this.setStatePromise({progress: 1}); // not shown to the user await doMuchWork(); await this.setStatePromise({progress: 2}); // not shown to the user await doEvenMoreWork(); await this.setStatePromise({progress: 3}); // shown to the user when everything is done};onButtonClick = async () => { await this.longRunningTask();}这是一个显示问题的工作示例:https://codesandbox.io/s/intelligent-cori-31qn5我之前使用的解决方法是:setStatePromise = (state) => new Promise(resolve => { this.setState(state, () => { setTimeout(() => resolve(), 1); });});
添加回答
举报
0/150
提交
取消