RTK Query的error、isError、isSuccess状态不更新且返回undefined如何解决
问题原因及对应解决方案
1. 未正确配置Redux Store(最高概率)
RTK Query需要你将对应api的reducer和中间件注册到全局store中,否则请求状态无法同步到组件,自然会返回undefined。
你需要修改你的Redux store配置,补充如下内容:
import { configureStore } from '@reduxjs/toolkit' import { companyApi } from './services/companyApi' // 其他你自己的reducer导入 export const store = configureStore({ reducer: { // 你的其他reducer [companyApi.reducerPath]: companyApi.reducer, // 必须和你定义的reducerPath一致 }, middleware: (getDefaultMiddleware) => // 必须注册api对应的中间件,用来处理缓存、状态更新等逻辑 getDefaultMiddleware().concat(companyApi.middleware), })
2. 写操作错误使用query定义,应该用mutation
DELETE属于数据变更类操作,RTK Query中这类操作需要用builder.mutation定义,query是专门给只读的查询请求设计的,默认的缓存、重试逻辑会导致状态更新不符合预期。
修改你的service代码:
endpoints: (builder) => ({ // 把builder.query改成builder.mutation deleteCompany: builder.mutation<ICompanyDeleteResponse, ICompanyDeleteRequest>({ query: ({ companyId }) => ({ url: `non_exists_url`, method: 'DELETE', headers: { 'X-CompanyId': companyId, }, }), }) }), // 导出的hook对应改为mutation格式 export const { useDeleteCompanyMutation } = companyApi
3. 组件调用方式不匹配
mutation的hook返回值是数组,第一项是触发请求的函数,第二项才是状态对象,你需要调整组件内的调用逻辑:
export const DeleteCompany: FC = () => { // mutation的用法和query不同,需要手动触发请求 const [deleteCompany, { data, error, isError }] = useDeleteCompanyMutation() const companyId = 1 // 组件挂载时触发删除请求 useEffect(() => { deleteCompany({ companyId }) // 入参要和定义的ICompanyDeleteRequest结构一致,传对象不要直接传数字 }, [deleteCompany, companyId]) useEffect(() => { console.log('data', data) console.log('error', error) console.log('isError ', isError ) }, [data, error, isError ]) return ( <div> 测试文本 </div> ) }
完成以上三处修改后,你就能正常拿到error和isError的值了。
内容的提问来源于stack exchange,提问作者Israel
相关产品推荐
相关产品推荐

