您正确地声明.toHandlers()生成POST /posts和PUT /posts/:id请求处理程序。RTK-Query 示例显式添加了这些处理程序,原因如下:
Math.random()通过根据处理程序中的值返回错误响应来模拟不稳定的错误行为。
- 将主键设置
idnanoid()为.
如果您删除显式POST /posts处理程序,则添加帖子会失败,因为模型定义post 没有定义id主键的初始值。如果不向实体提供主键,则无法创建实体,示例中没有:
// PostManager.tsx
// The "post" state only contains the name of the new post.
const [post, setPost] = useState<Pick<Post, "name">>(initialValue);
// Only the "post" state is passed to the code that dispatches the
// "POST /posts" request handled by MSW.
await addPost(post).unwrap();
如果我们省略随机错误行为,我认为该示例应该用作模型描述中属性nanoid的初始值:id
import { nanoid } from "@reduxjs/toolkit";
const db = factory({
post: {
- id: primaryKey(String),
+ id: primaryKey(nanoid),
name: String
}
});
这样您就可以通过提供name唯一的来创建新帖子。主键的值id将使用 value getter(该nanoid函数)生成。
即使您删除了显式PUT /posts/:id请求处理程序,帖子编辑操作也能正常运行,因为与POST处理程序不同的是,该处理程序PUT 仅用于实现易碎的错误行为(路径参数中提供了已编辑的帖子 ID:)req.params.id。