现象
修改antd的Col组件的layouts属性为span后,并通过监听resize事件对span列宽进行动态变化时,报错TypeError: Cannot read properties of undefined (reading ‘then‘)
。
补充示例一
由于我使用了飞冰ice.js
,且在以下过程中写了如下语句,引起了同样的报错!
import {
useRequest as useRequestHook } from 'ice';
const {
data } = useRequest(
() => wareHouseModel.data && homeService.getAllFixedAssets(wareHouseModel.data, tenantCode),
{
manual: false,
withFullResult: true,
refreshDeps: [wareHouseModel.data],
ready: !!tenantCode,
},
);
关键报错代码:
wareHouseModel.data && homeService.getAllFixedAssets(wareHouseModel.data, tenantCode),
正是因为wareHouseModel.data &&
的与逻辑引起了该TypeError: Cannot read properties of undefined (reading ‘then‘)
报错,因为如果wareHouseModel.data
没有值,会导致返回的是非promise
的对象!!!
antd引起该错误的代码示例二
const Home = () => {
const [colSpan, setColSpan] = React.useState<number>(12);
React.useLayoutEffect(() => {
// 自适应每屏显示坐标点数量设置
const resizeColSpan = () => {
const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let spanNum = 0;
if (+width >= 1415 && +width < 1850) {
spanNum = 8;
}
if (+width >= 1850) {
spanNum = 6;
}
setColSpan(spanNum);
};
// 初始时需要触发resize,否则会有样式兼容问题
resizeColSpan();
const onResize = debounce(() => {
resizeColSpan();
}, 50);
window.addEventListener('resize', onResize);
return () => {
window.removeEventListener('resize', onResize);
};
}, []);
// ...以下省略部分内容
return (
{
/* <Col {...layouts} className={`${styles['panel-item']} panel-item`}> */}
<Col span={
colSpan} className={
`${
styles['panel-item']} panel-item`}>
{
React.isValidElement(children) &&
React.cloneElement(children as React.ReactElement, {
onClick: (actionKey) => handleClick(actionKey, item),
hasRemoved: panelList.length >= 3,
})}
</Col>
);
报错原因
由于上面的代码给了一个let spanNum = 0;
,默认给0的情况会引起获取不到元素的报错。将其赋值为let spanNum = 12;
即可。