如何指定何时重新触发钩子
我正在尝试更新我的React工具知识,添加RTK
正在浏览 RTK查询
https://redux-toolkit.js.org/rtk-query/overview
最终以这样的somwthing:
export const todoApi = createApi({
reducerPath: 'todoApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://jsonplaceholder.typicode.com/' }),
endpoints: (builder) => ({
getAllTodos: builder.query<Task[], string>({
query: () => `todos`,
}),
}),
})
// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetAllTodosQuery } = todoApi
slice中:
export const todoSlice = createSlice({
name: "todo",
initialState,
reducers: {
addTask: //[...],
toggleTask: // [...],
fillTodos: (state, action: PayloadAction<Task[]>) => {
// debugger;
state.todos = action.payload
}
}
});
在 m试图从API中拉出:
export function Todo() {
const todos = useSelector((state: RootState) => state.todo.todos);
const dispatch = useDispatch();
const { data, error, isLoading } = useGetAllTodosQuery("")
if (data) {
dispatch(fillTodos(data));
}
这将粗略地工作,用拉的 todos
更新商店,但它会触发 usegetAltOdoSquery
每次component reconenter (甚至甚至安装时或使用无关动作更新商店时几次 - 完成任务 - )。 Kinda正在寻找类似于 usefect
param的类似方法,以指定何时再次触发效果。
我想我缺少一些基本知识。
想法?谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,它不会多次换取。它一次获取。
然后数据在缓存中,并且在结果手动调用
.refetch
之后,它不会提出请求,或者将自动置换功能与providestags/invalidateStags一起使用。如果您想更深入地进入RTK查询,请关注
PS:如果可以避免,则不应将这些数据真正复制到您自己的切片中。只需调用
使用...查询
在需要该数据的任何地方都具有相同参数的挂钩。It actually does not refetch multiple times. It fetches once.
And then data is in the cache and it does not make a request until you manually call
.refetch
on the result, or use the automatic refetching feature with providesTags/invalidatesTags.If you want to get deeper into RTK Query, follow chapter 7 and 8 of the official Redux tutorial
PS: you should not really copy that data out of RTK Query into your own slices if you can avoid it. Just call the
use...Query
hook with the same argument everywhere you need that data.