我使用RTK查询来获取数据,在其中一个用例中遇到了一个小问题.
我使用一种Mutations 来验证应用程序用户的邮箱地址,如下所示:
// ...imports
const ConfirmEmail = () => {
const [params] = useSearchParams();
const [confirmEmail, { isLoading, isSuccess, isUninitialized, error }] =
useConfirmEmailMutation();
useEffect(() => {
if (isUninitialized) {
confirmEmail({
email: params.get('email'), // from the verification link
code: params.get('code'), // from the verification link
})
.unwrap()
.then(() => {
// handling success...
})
.catch((e) => {
// handling error...
});
}
});
// ...other component code
}
问题是,对于StrictMode
,Mutations 在开发中运行两次,并且它在API端导致并发错误.我在开发工具中看到两个网络请求,一个是成功的,另一个是不成功的,根据哪个先运行,组件会显示不一致的结果.
我知道这只会发生during development,我试着遵循说明in the official react documentation,我试着使用fixedCacheKey
,就像所描述的here,但我不能使用RTK查询,所以我得到了一致的结果during development.
有什么办法吗,还是我错过了什么?
Edit:我的问题与this question属于同一类别,但它更具体地针对RTK查询.因为在RTK查询中,如果组件试图进行与现有组件相同的查询,则不会执行任何请求(如前面提到的here).然而,我试图做的是一种Mutations ,以确认用户的邮箱地址(在点击通过邮箱发送的链接后).Mutations 并不遵循前面提到的here号规则.
useEffect
清理功能没有帮助,这不像buying a product个例子.
根据下面的讨论,可用的选项是:
- 使用查询而不是Mutations .但这不会是语义上的 对,是这样.
- 强制用户再次点击某个按钮以启动"确认邮箱"Mutations .这是重复的,而且对用户不友好.
- 使用
ref
来跟踪Mutations 是否已经在运行.这是我在最后实现的,如下所示:
// ...imports
const ConfirmEmail = () => {
const verifiying = useRef(false);
const [params] = useSearchParams();
const [confirmEmail, { isLoading, isSuccess, isUninitialized, error }] =
useConfirmEmailMutation();
useEffect(() => {
const isVerifying = verifiying.current;
if (isUninitialized) {
verifiying.current = true;
confirmEmail({
email: params.get('email'), // from the verification link
code: params.get('code'), // from the verification link
})
.unwrap()
.then(() => {
// handling success...
})
.catch((e) => {
// handling error...
});
}
});
// ...other component code
}