Files
stack/packages/stack-idealjs/docs/advance/pure_function.md
T
2026-08-19 13:23:30 +08:00

64 lines
1.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
sidebar_position: 1
---
# 纯函数与副作用
## 什么是纯函数
纯函数需要同时满足两个条件
1. 相同的输入,总是返回相同的输出
2. 执行过程中不产生任何副作用
```ts
// 纯函数:只依赖入参,不修改外部状态
function add(a: number, b: number): number {
return a + b;
}
```
```ts
let count = 0;
// 非纯函数:修改了外部变量,产生了副作用
function increase(): number {
count += 1;
return count;
}
```
## 什么是副作用
副作用是指函数在执行过程中,对外部环境产生了影响。常见的副作用包括
- 修改外部变量或对象属性
- 发起网络请求
- 操作 DOM
- 读写文件、数据库
- `console.log`
## 为什么要区分
纯函数具有可预测性:只要输入确定,输出就确定。这使得
- **易于测试**:不需要 mock 外部环境
- **易于缓存**:相同输入可以直接返回缓存结果
- **易于推理**:阅读代码时不需要追踪外部状态
在前端框架中,这个概念随处可见。React 的函数组件在渲染阶段就要求保持纯净,副作用被统一收拢到 `useEffect` 中,本质上就是把"计算"和"影响外部世界"这两件事分开。
## 实践建议
1. 尽量把视图渲染逻辑写成纯函数,输入输出清晰
2. 把副作用集中在边界处(入口、事件回调、`useEffect`)
3. 修改数据时,不直接改动原数据,而是返回新的副本。(或者依赖框架的修改能力)
```ts
// 直接修改原数组(副作用)
list.push(item);
// 返回新数组(无副作用)
const newList = [...list, item];
```