阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > 接口定义规范

接口定义规范

作者:陈川 阅读数:20792人阅读 分类: 前端综合

组件开发和接口定义是前端工程化的核心环节,规范的制定直接影响代码的可维护性和团队协作效率。从组件设计原则到接口约定,需要明确的标准约束开发行为,避免出现风格混乱或沟通成本过高的问题。

组件开发规范

文件结构约定

采用扁平化目录结构,每个组件独立成包。典型结构示例:

components/
├─ button/
│  ├─ index.tsx       // 主入口
│  ├─ style.module.scss
│  ├─ Button.test.tsx
│  └─ README.md       // 组件文档

命名规则

  • PascalCase命名组件文件:DatePicker.tsx
  • kebab-case命名样式文件:date-picker.module.scss
  • 测试文件后缀:ComponentName.test.tsx

Props设计原则

  1. 保持props原子性,避免万能props:
// 错误示范
interface Props {
  variant: 'text' | 'outlined' | 'contained'
}

// 正确做法
interface Props {
  text?: boolean
  outlined?: boolean
  contained?: boolean
}
  1. 必选props放前面,可选props放后面:
interface ModalProps {
  open: boolean
  title: string
  onClose?: () => void
  width?: number
}

状态管理

  • 组件内部状态使用useState/useReducer
  • 复杂状态逻辑封装为自定义hook:
function useToggle(initial = false) {
  const [state, setState] = useState(initial)
  const toggle = useCallback(() => setState(v => !v), [])
  return [state, toggle] as const
}

样式方案

  1. CSS Modules优先于全局样式
  2. 设计变量集中管理:
// variables.scss
$primary-color: #1890ff;
$breakpoint-md: 768px;

接口定义规范

RESTful约定

  1. 资源命名使用复数名词:
GET /api/users
POST /api/articles
  1. 状态码标准化:
  • 200 OK - 常规成功响应
  • 201 Created - 资源创建成功
  • 400 Bad Request - 参数校验失败
  • 401 Unauthorized - 未认证
  • 403 Forbidden - 无权限

请求/响应格式

  1. 请求体统一为JSON:
{
  "user": {
    "email": "user@example.com",
    "password": "securepassword"
  }
}
  1. 响应包装结构:
interface ApiResponse<T> {
  code: number
  data: T
  message?: string
  timestamp: number
}

TypeScript接口定义

  1. 使用泛型处理分页数据:
interface Pagination<T> {
  current: number
  pageSize: number
  total: number
  items: T[]
}

interface User {
  id: string
  name: string
  avatar?: string
}

type UserListResponse = ApiResponse<Pagination<User>>
  1. 参数校验类型:
interface CreateUserParams {
  username: string
  password: string
  age?: number
  readonly createdAt: Date
}

错误处理

  1. 定义错误码枚举:
enum ErrorCodes {
  INVALID_TOKEN = 1001,
  RESOURCE_NOT_FOUND = 2004,
  DUPLICATE_ENTRY = 3009
}
  1. 前端错误拦截示例:
axios.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

版本控制策略

API版本管理

  1. URL路径版本控制:
/api/v1/users
/api/v2/users
  1. 请求头版本控制:
GET /api/users
Accept-Version: 1.1.0

组件版本管理

  1. 遵循语义化版本:
  • MAJOR:不兼容的API修改
  • MINOR:向下兼容的功能新增
  • PATCH:向下兼容的问题修正
  1. changelog示例:
## 1.2.0 (2023-08-15)

### Features
- 新增dark mode支持
- 增加键盘导航功能

### Fixes
- 修复dropdown定位问题 (#123)

文档化要求

组件文档

  1. Props表格示例: | 属性名 | 类型 | 默认值 | 说明 | |-------|------|-------|------| | size | 'small'|'medium'|'large' | 'medium' | 控制按钮尺寸 | | block | boolean | false | 是否撑满容器宽度 |

  2. 代码示例展示:

<Button 
  type="primary" 
  onClick={() => alert('Confirmed')}
>
  确认操作
</Button>

API文档

  1. Swagger注解示例:
paths:
  /users/{id}:
    get:
      tags: [User]
      parameters:
        - $ref: '#/parameters/userId'
      responses:
        200:
          description: 用户详情
          schema:
            $ref: '#/definitions/User'
  1. 接口示例响应:
{
  "code": 200,
  "data": {
    "id": "usr_123",
    "name": "张三",
    "email": "zhangsan@example.com"
  },
  "timestamp": 1692086400000
}

性能优化要点

组件层面

  1. 避免不必要的渲染:
const MemoComponent = React.memo(Component, (prev, next) => {
  return prev.value === next.value
})
  1. 虚拟滚动实现:
<VirtualList
  itemHeight={40}
  itemCount={1000}
  renderItem={({ index, style }) => (
    <div style={style}>Row {index}</div>
  )}
/>

接口层面

  1. 分页参数默认值:
interface ListParams {
  page?: number
  size?: number
  sort?: string
}

const DEFAULT_PAGE_SIZE = 20
  1. 响应压缩配置:
server {
  gzip on;
  gzip_types application/json;
}

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:目录结构规范

下一篇:Git核心知识点

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌