首页 > 其他分享 >[React] Force React to update it's DOM by using flushSync

[React] Force React to update it's DOM by using flushSync

时间:2024-07-31 14:29:30浏览次数:19  
标签:react Force DOM isPrinting flushSync React window print

Refer to https://react.dev/reference/react-dom/flushSync

 

For example, the browser onbeforeprint API allows you to change the page immediately before the print dialog opens. This is useful for applying custom print styles that allow the document to display better for printing. In the example below, you use flushSync inside of the onbeforeprint callback to immediately “flush” the React state to the DOM. Then, by the time the print dialog opens, isPrinting displays “yes”:

Without flushSync, the print dialog will display isPrinting as “no”. This is because React batches the updates asynchronously and the print dialog is displayed before the state is updated.

import { useState, useEffect } from 'react';
import { flushSync } from 'react-dom';

export default function PrintApp() {
  const [isPrinting, setIsPrinting] = useState(false);

  useEffect(() => {
    function handleBeforePrint() {
      flushSync(() => {
        setIsPrinting(true);
      })
    }

    function handleAfterPrint() {
      setIsPrinting(false);
    }

    window.addEventListener('beforeprint', handleBeforePrint);
    window.addEventListener('afterprint', handleAfterPrint);
    return () => {
      window.removeEventListener('beforeprint', handleBeforePrint);
      window.removeEventListener('afterprint', handleAfterPrint);
    }
  }, []);

  return (
    <>
      <h1>isPrinting: {isPrinting ? 'yes' : 'no'}</h1>
      <button onClick={() => window.print()}>
        Print
      </button>
    </>
  );
}

 

标签:react,Force,DOM,isPrinting,flushSync,React,window,print
From: https://www.cnblogs.com/Answer1215/p/18334530

相关文章

  • RandomCrop 导致 INVALID_ARGUMENT:所需的可广播形状
    我正在使用Keras训练神经网络,并尝试使用RandomCrop层。我正在使用动态大小的数据集(不同的分辨率),但我发现它目前不是此问题的原因。当我运行model.fit()时,不久之后,我收到上述错误|||。我能够获得模型的摘要,因此那里不存在一些不匹配。INVALID_ARGUM......
  • 在react中使用Particles
    stepone首先封装一个粒子效果组件,option各项配置在tsparticles/react有介绍。//ParticleBackground.jsimportReact,{useEffect,useState}from"react";import{loadSlim}from"@tsparticles/slim";importParticles,{initParticlesEngine}from"@......
  • Educational Codeforces Round 168 (Rated for Div. 2) 补题记录(A~E)
    A直接暴力枚举字符添加在哪里,以及添加的字符是什么即可。#include<bits/stdc++.h>#defineintlonglongusingnamespacestd;constintN=500100;signedmain(){intT;cin>>T;while(T--){strings;cin>>s;stringans;i......
  • [vue3] Vue3源码阅读笔记 reactivity - collectionHandlers
    源码位置:https://github.com/vuejs/core/blob/main/packages/reactivity/src/collectionHandlers.ts这个文件主要用于处理Set、Map、WeakSet、WeakMap类型的拦截。拦截是为了什么?为什么要处理这些方法?Vue3实现响应式的思路是使用ProxyAPI在getter中收集依赖,在setter触发更新......
  • [vue3] Vue3源码阅读笔记 reactivity - collectionHandlers
    源码位置:https://github.com/vuejs/core/blob/main/packages/reactivity/src/collectionHandlers.ts这个文件主要用于处理Set、Map、WeakSet、WeakMap类型的拦截。拦截是为了什么?为什么要处理这些方法?Vue3实现响应式的思路是使用ProxyAPI在getter中收集依赖,在setter触发更新......
  • Codeforces Round 933 (Div. 3) D 题
    D.RudolfandtheBallGame原题链接:https://codeforces.com/contest/1941/problem/D RudolfandBernarddecidedtoplayagamewiththeirfriends. n peoplestandinacircleandstartthrowingaballtoeachother.Theyarenumberedfrom 1 to nn i......
  • Codeforces Round 929 (Div. 3)---->E. Turtle vs. Rabbit Race: Optimal Trainings
    https://codeforces.com/contest/1933/problem/E#include<bits/stdc++.h>#definexfirst#defineysecondusingnamespacestd;typedeflonglongll;typedef__int128i128;typedefpair<int,int>pii;constintN=2e5+10,M=110;intn,q;inta[N];ll......
  • 强化学习Reinforcement Learning算法的样本效率提升策略
    强化学习ReinforcementLearning算法的样本效率提升策略1.背景介绍1.1问题的由来在强化学习领域,提升算法的样本效率是关键挑战之一。在许多现实世界的应用场景中,比如机器人自主导航、智能游戏、自动驾驶、医疗健康决策以及大规模服务系统优化,获取高价值的环境反馈往往......
  • 上传多个图像时 React 前端和 Flask 后端出现 CORS 策略错误
    实际上,我已经在reactJs中制作了前端,在pythonFlask中制作了后端(使用cnn模型进行一些预测)。当我按照我的请求发送5到6张图像时,它工作正常,但是当我发送10到15张图像和一些时间时令人筋疲力尽,然后它给出了类似的错误,尽管我在下面给出的代码中设置了Cors:192.168.151.24/:1Accesst......
  • 鼠标滚动判断dom元素是否在可视区
    1、利用IntersectionObserver监听dom元素<divclass="box_over"><ul><liv-for="(item,index)in10":style="`background:rgb(${255*Math.random()*2},${255*Math.random()*2},${255*Math.random()*4})`"......