console.log失效了?

console.log 作为前端工程师非常值得信赖的调试工具,居然失效了???没想到啊没想到,console.log 这么个浓眉大眼的家伙,居然也…

先直接上代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import { useState } from 'react';
import { Upload } from 'antd';
const MyUpload = () => {
const [fileList, setFile] = useState([]);
const handleChange = (info) => {
console.log(999, info);
let newList = info.fileList;
console.log(11, newList);
newList.push(2);
newList.push(3);
console.log(222, newList);
newList = newList.map((file) => {
if (file.response) {
file.url = file.response.url;
}
return file;
});
};
const props = {
action: 'https://www.mocky.io/',
onChange: handleChange,
multiple: true,
};
return (
<Upload {...props} fileList={fileList}>
<Button>Upload</Button>
</Upload>
);
};

由上图可以看到,无论是 999 还是 11,都输出了它们本不该输出的内容,也就是在console.log(11, newList)之后才 push 的数字 2 和 3。

于是我打开了 vscode 调试工具,断点调试如下图: 由图可以看出,在newList.push(2)之前,数组并没有包含 2 这个数字。

在 Chrome 里面调试也没有问题。

经推测,应该是异步引起的问题(示例代码没有提到异步,由于时间有些久远,原代码和示例代码可能会有一点点出入,我以后要尽量及时整理,抱歉。不过当出现 console.log 与预期不一致的情况下,依旧可以使用本文中提到的方法),方法如下:

首先检查项目有关 console.log 的地方,有没有被重写,是不是有哪些地方实现了window.console.log;如果没有的话,接下来弃用console.log而使用alert,此次就是在这个地方检查出来了错误。

直接用 alert 可能会打印不出来数据,出现下面这样的情况:

要用JSON.stringfy

所以,问题找到啦,是console.log的问题,可以采用下面这种写法:

Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2018-2020 Jee
  • Visitors: | Views:

如果您觉得此文章帮助到了您,请作者喝杯咖啡吧~

支付宝
微信