reactjs - 在开玩笑测试中安装组件之前运行的 useEffect
问题描述
useEffect 似乎在安装组件之前运行,当我对渲染中的元素执行 document.getElementsByClassName 时,它是未定义的。它不是有条件地渲染或任何东西。
我正在使用最新的笑话,酶配置了适配器 16。有谁知道发生了什么?
从我所看到的正确配置它,没有错误
const IndustriesGraphic = () => {
const canvas = useRef(null);
useEffect(() => {
const { clientWidth, clientHeight } = document.getElementsByClassName('industries-graphic__canvas-container')[0];
canvas.current.style.width = `${clientWidth}px`;
canvas.current.style.height = `${clientHeight}px`;
const scale = clientWidth < clientHeight ? clientWidth : clientHeight;
createGraphic(scale);
const resizeGraphic = () => {
const canvasContainer = document.getElementsByClassName('industries-graphic__canvas-container')[0];
if (!canvasContainer) {
return;
}
const { clientWidth: newWidth, clientHeight: newHeight } = canvasContainer;
canvas.current.style.width = `${newWidth}px`;
canvas.current.style.height = `${newHeight}px`;
const newScale = newWidth < newHeight ? newWidth : newHeight;
createGraphic(newScale);
};
window.addEventListener('resize', resizeGraphic);
return window.removeEventListener.bind(null, 'resize', resizeGraphic);
}, []);
return (
<div className="industries-graphic">
<h1 className="industries-graphic__header">{industriesConfig.header}</h1>
<div className="industries-graphic__canvas-container">
<canvas ref={canvas} id={CANVAS_ID} />
</div>
<div className="industries-graphic__tablet-graphic">
<span className="industries-graphic__tablet-icon">
<img src={cryptoIcon} alt="crypto" />
</span>
<span className="industries-graphic__tablet-icon">
<img src={securityIcon} alt="crypto" />
</span>
<span className="industries-graphic__tablet-icon">
<img src={financialIcon} alt="crypto" />
</span>
<span className="industries-graphic__tablet-icon">
<img src={entertainmentIcon} alt="crypto" />
</span>
<span className="industries-graphic__tablet-icon">
<img src={socialIcon} alt="crypto" />
</span>
<span className="industries-graphic__tablet-icon">
<img src={medicalIcon} alt="crypto" />
</span>
</div>
<div className="industries-graphic__scroll-text">SCROLL TO CONTINUE</div>
</div>
);
};
我希望 useEffect 在渲染后运行,但由于某种原因该组件尚未安装
解决方案
推荐阅读
- c# - 使用 EF Core 在 linq 中使用索引的嵌套选择投影
- geospatial - 如何在 Geogam 分析中包含分类协变量?
- java - 通过 http 运行 livy 作业,无需每次都上传 jar
- xamarin - 在 Xamarin UWP 应用程序中从远程网络共享打开文件
- r - R 如何制作 .pkg 文件以在 Mac OS X 上安装?
- java - 两个异步任务在android studio中不能同时工作
- java - 限制每次执行结构化流查询时扫描的 S3 分区
- javascript - 无法将子主题中的脚本排入队列
- ios - 在 appDelegate 中的 didReceiveRemoteNotification 方法的 Present 模式后推送控制器
- c# - Livecharts Scatter Plot:为轴标签设置自定义数字