gpt4 book ai didi

javascript - 在 Chrome 中禁用缓存的情况下 React Rerender

转载 作者:行者123 更新时间:2023-12-03 17:22:28 32 4
gpt4 key购买 nike

我有一个 react 应用程序,我在其中使用“react-image-pan-zoom-rotate”来显示图像。
https://github.com/mgorabbani/react-image-pan-zoom-rotate
我基本上有一个外部服务的 url,它提供了我传递给以下两个库以呈现图像的图像。
最近我开始面临一个问题(仅在 Chrome 中),如果缓存被禁用,那么每当我在浏览器中单击图像或使用此组件提供的任何控件时,它都会重新呈现它,从而导致再次调用外部图像服务器。每当我单击/与上述 react 库生成的图像或 View 交互时,就会发生这种情况。
现在我开始使用https://github.com/theanam/react-awesome-lightbox/blob/master/src/index.js并且在禁用缓存的情况下没有任何此类问题。
知道为什么会发生这种情况吗?

最佳答案

重现问题
我可以重现您描述的行为:https://codesandbox.io/s/n1rv671pkj
禁用缓存确实会导致每次重新下载图像。
问题
这是由于他们的实现(可以在这里看到 https://github.com/mgorabbani/react-image-pan-zoom-rotate/blob/master/src/PanViewer.tsx )他们设置 key={dx}

      <StyledReactPanZoom
zoom={zoom}
pandx={dx}
pandy={dy}
onPan={onPan}
rotation={rotation}
key={dx}
>
<img
style={{
transform: `rotate(${rotation * 90}deg)`,
}}
src={image}
alt={alt}
ref={ref}
/>
</StyledReactPanZoom>
解释
这告诉 react 在每次图像的 x 坐标发生变化时实例化一个新组件,并且没有缓存意味着重新下载图像(尝试仅垂直移动,您将看到没有重新加载)。要了解 key prop 导致新实例的原因,请参阅 react docs这个答案在 Understanding unique keys for array children in React.js
这是上面链接的答案的解释要点:

React uses the key prop to understand the component-to-DOM Elementrelation, which is then used for the reconciliation process. It istherefore very important that the key always remains unique,


...

It is also important that these keys remain staticthroughout all re-renders in order to maintain best performance.


解决方案
我创建了一个沙箱,我只删除了该行,它有效地停止了重新加载图像。
https://codesandbox.io/s/react-image-pan-zoom-rotate-forked-tn787?file=/src/index.tsx

关于javascript - 在 Chrome 中禁用缓存的情况下 React Rerender,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66599159/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com