RTK查询正确的方法与Transformponse映射道具
我正在努力将调度程序组件与通过RTK查询API调用接收的数据链接。为了使调度程序工作,我必须在状态在组件中可用之前将道具名称调整为调度程序所使用的名称(否则我在React组件中尝试时不会加载它)。在RTK查询文档中没有一个明确的例子( https://redux-toolkit.js.org/rtk-query/usage/customizing-ceries-quastomizing-quastomis#customist-customizing-query-responses-with-transpons-with-transformsponse )就像它应该有可能。当我实现它时,查询将得到满足,但作为一个空对象或一个带有单个空对象的数组返回,具体取决于我试图构造它的方式。
getUserScheduleVisits: builder.query({
query: userId => `/visitapi/visits/users/${userId}`,
providesTags: ['Visit', 'User'],
transformResponse: (response) => {
return {
data: [{
id: response._id,
startDate: response.visitStart,
endDate: response.visitEnd,
title: response?.client?.fullName
}]
}
},
}),
当我在没有转换响应的情况下运行查询时,数据会按预期进行,但是我要实现的调度程序组件仍然无法使用。我仍在学习RTK查询的复杂性,因此我确定它如何尝试使用Transform Response,我只是不确定如何正确处理它。
I'm working on linking up a scheduler component with data that I am receiving through an RTK Query api call. In order for the scheduler to work, I have to adjust the prop names to names the scheduler utilizes, before the state is available in the component (otherwise it does not load when I've tried in the React component). There is not a clear example of this being done in the RTK Query docs (https://redux-toolkit.js.org/rtk-query/usage/customizing-queries#customizing-query-responses-with-transformresponse) , but it seems like it should be possible. When I've implemented it, the query gets fulfilled, but comes back as an empty object, or an array with a single empty object depending on how I've tried to structure it.
getUserScheduleVisits: builder.query({
query: userId => `/visitapi/visits/users/${userId}`,
providesTags: ['Visit', 'User'],
transformResponse: (response) => {
return {
data: [{
id: response._id,
startDate: response.visitStart,
endDate: response.visitEnd,
title: response?.client?.fullName
}]
}
},
}),
When I've run the query without the transform response, the data comes through as expected, however remains unusable by the Scheduler component I'm trying to implement. I'm still learning the complexities to RTK Query so I'm sure its how I'm trying to use transformResponse, I'm just not sure how to approach it correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您执行
const result = usemyquery()
,这将最终成为result.data.data
。您可能是要这样做吗?
This would end up as
result.data.data
if you doconst result = useMyQuery()
.Did you maybe mean to do this?
确保您不是RunNign Redux persistor,否则变换将“似乎没有触发”,但您需要清除局部孔,以便persistor会刷新。
Make sure you are NOT runnign Redux Persistor, otherwise transform will 'appear to be not triggering', but you need to clear the localStorage, so that persistor will refresh.