如何在rtk查询中使用useEffect更新状态



我有两个端点,当我添加新的值到端点1,我希望端点2更新的useEffect钩子

const PostDetails = (props) => {
const id = props.match.params.id;
const [addNewComment, { isSuccess: success, isError }] = useAddNewCommentMutation();

const dispatch = useDispatch();
const selectPost = useMemo(() => postApi.endpoints.getPost.select(id), [id]);
const { data: post, isLoading } = useSelector(selectPost);
useEffect(() => {
const result = dispatch(postApi.endpoints.getPost.initiate(id));
return result.unsubscribe;
}, [id, dispatch, success]);

名称(销):"ConditionError"message(pin):"Aborted由于条件回调返回false.">

这意味着"已经有数据了,我没有理由认为它过时了,我不会再取回数据了"

做一个

dispatch(postApi.endpoints.getPost.initiate(id, {forceRefetch: true}));

但这不是你应该做的。

你真正应该使用的是invalidation特性。

您的端点getPost有一个返回[{ type: 'Post', id: 5 }]providesTags函数,您的addNewComment突变也有一个返回[{ type: 'Post', id: 5 }]invalidatesTags函数。

这样,无论何时调用addNewComment突变,getPost端点都会重新获取。

请阅读关于自动重新抓取的文档章节

最新更新