safety-eval-service-frontend/.cursor/skills/declare-request-usage/SKILL.md

89 lines
2.2 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

---
name: "declare-request-usage"
description: "规范使用 declareRequest 声明 API 并在组件中通过 props 调用的模式。当新增/调用 declareRequest 声明的接口时,必须遵循此规范。"
---
# declareRequest 使用规范
## 核心原则
**不要直接 import `declareRequest` 声明的函数并直接调用。** 必须通过 `Connect` 注入的 `props` 访问。
## 正确步骤
### 1. 声明 API (在 `src/api/` 下)
```js
// src/api/xxx/index.js
import { declareRequest } from "@cqsjjb/jjb-dva-runtime";
export const someApi = declareRequest(
"xxxLoading", // loading key与 namespace 同名前缀
"Get > /path/to/api", // 请求方式与路径
"someData: [] | res.data || []", // 响应数据映射(可选)
);
```
### 2. 使用 API (在页面组件中)
**正确**:通过 `Connect` 注入的 `props` 访问
```jsx
import { Connect } from "@cqsjjb/jjb-dva-runtime";
import { NS_XXX } from "~/enumerate/namespace";
function MyPage(props) {
const handleLoad = () => {
// ✅ 通过 props 调用
props.someApi(params).then((res) => {
// 处理结果
});
};
}
export default Connect(
[NS_XXX], // 传入正确的 namespace
true,
)(MyPage);
```
**正确**:父组件通过 props 传递给子组件
```jsx
// 父组件
function Parent(props) {
return <Child someApi={props.someApi} />;
}
// 子组件通过 props 接收
function Child({ someApi }) {
const handleLoad = () => {
someApi(params); // ✅ 正确
};
}
```
**错误**:直接 import 并调用
```jsx
// ❌ 错误!不要这样做
import { someApi } from "~/api/xxx";
function MyComponent() {
// ❌ someApi 不是可调用的函数
someApi(params);
}
```
## 为什么
`declareRequest` 注册的是 Redux action需要通过 `Connect` 绑定到组件的 props 后才能正常工作。直接 import 得到的不是可调用的函数,会导致 `is not a function` 错误。
## 检查清单
- [ ] API 声明在 `src/api/` 下的对应文件中
- [ ] `declareRequest` 的 loading key 与 namespace 的 loading 前缀一致
- [ ] 组件通过 `Connect([NS_XXX], true)` 连接
- [ ] 通过 `props.apiName(params)` 调用,而非直接 import 调用
- [ ] 子组件需要的 API 函数通过 props 从父组件传入