🪤 写了 5 年前端,我还在踩这些“低级”坑
“代码写了不少,bug 还是天天有。”
😵💫 1.setTimeout和setInterval的坑
❌ 以前我写:
setTimeout(() => {
console.log(this.name);
}, 1000);
-
this 是谁?没人知道。****
-
结果是 undefined,还以为是 bug。
✅ 现在我写:
setTimeout(() => {
console.log(this.name);
}, 1000);
- 永远用箭头函数,this 就不会跑丢。
🧠 2.map不等于forEach
❌ 以前我写:
const arr = [1, 2, 3];
arr.map(item => console.log(item));
-
忘了 map 是有返回值的,白白浪费计算。
✅ 现在我写:
arr.forEach(item => console.log(item));
- 想要副作用就用 forEach,想要返回新数组才用 map。
🤦 3. “我以为我能掌控 setState”
❌ 以前我写:
const [count, setCount] = useState(0);
setCount(count + 1);
setCount(count + 1);
-
结果只加了 1,不是 2 😭
✅ 现在我写:
setCount(prev => prev + 1);
setCount(prev => prev + 1);
- 函数式更新,永远不会错。
📐 4. CSS 不要写死
width: 100%
❌ 以前我写:
.container {
width: 100%;
}
-
图片、文本一多,全崩了。
✅ 现在我写:
.container {
max-width: 100%;
overflow: hidden;
}
- 防止撑爆布局。
🧩 5. “我以为 Flex 就不会塌”
❌ 以前我写:
.flex-container {
display: flex;
}
-
结果子元素塌了,站不稳。
✅ 现在我写:
.flex-container {
display: flex;
flex-wrap: wrap;
}
- 或者直接加个 gap 也行。
📦 6. “我以为 npm 和 yarn 一样”
❌ 以前我写:
npm install
yarn start
-
一堆 node_modules 冲突,崩溃。
✅ 现在我写:
rm -rf node_modules
yarn install
- 要么全 npm,要么全 yarn,不混用。
🛠 7. “我以为 LocalStorage 是安全的”
❌ 以前我写:
localStorage.setItem("token", "123456");
-
结果被脚本攻击、token 泄漏。
✅ 现在我写:
- 要么用 sessionStorage
- 要么后端设置 HttpOnly cookie
📬 写在最后
这些坑你踩过几个?
我写了 5 年前端,这些坑到现在还在踩。
有兴趣的可以一起聊聊你踩过的最“低级”bug,说不定咱们能凑个“踩坑集锦”。