Redux 工具包 RTK 查询突变未获取返回数据

问题描述 投票:0回答:3

嗨,我最近学习了带有 rtk 查询工具的新 React 工具包,并且我正在尝试使用 rtk 包中的

createApi
一起放入登录系统。

在按下登录按钮后进行测试后,我看到网络请求没有任何问题(状态代码 200),并且我得到一个提供

user
token
的响应对象,但是,当我尝试获取使用
useLoginMutation
返回数据,我得到一个未定义的值。

下面是我的端点的代码,它被注入到基本 api 中:

export const apiLogin = theiaBaseApi.injectEndpoints({
  endpoints: (build) => ({
    loginUser: build.mutation<UserReadonly, loginValuesType | string>({
      query: (values: loginValuesType, redirect?: string) => {
        const { username, password } = values;
        const header = gettingSomeHeaderHere

        return {
          url: "login",
          method: "GET",
          headers,
          crossDomain: true,
          responseType: "json",
        };
      },
    }),
  }),
});

export const { useLoginUserMutation } = apiLogin

然后在我的 React 组件中我解构突变结果,如下所示:

const [login, {data, isLoading}] = useLoginUserMutation();

const submitLogin = () => {
  // pass in username password from the form
  login({username, password});
}

假设如果我控制台注销

data
isLoading
我假设我会看到
data: {user: "abc", token: "xyz"}
,因为在我的检查窗口的网络选项卡下我可以看到此网络请求的响应,但我看到的是
data: undefined

有没有人有解决这个问题的经验?

reactjs react-redux react-hooks redux-toolkit rtk-query
3个回答
6
投票

哦,我找到原因了,这是一个非常粗心的错误。我必须将减速机包装到我的商店,这正是我所缺少的


1
投票

就我而言,问题是我试图访问

UseMutationResult
回调中的
onClick
对象。即使在组件中值是准确的,对象也不会在回调内更新。

如果我把日志放在外面,它就可以正常工作。 这里是一个更好理解的例子(在handleAddPost中,mutationResult没有更新)

这是一个代码示例(以防链接不起作用):

const Component = () => {
  const [addPost, mutationResult] = useAddPostMutation();
  ...
  const handleAddPost = async () => {
      ...
      console.log("INSIDE CALLBACK isLoading and other data is not updating:");
      console.log(JSON.parse(JSON.stringify(mutationResult)))
      ...
  };
  // in the example this is wrapped in an useEffect to limit the number of logs
  console.log(mutationResult.data,"OUTSIDE CALLBACK isLoading and other data is working:")
  console.log(JSON.parse(JSON.stringify(mutationResult)))

  return (
  ...
    <Button
      ...
      onClick={handleAddPost}
    >
      Add Post
    </Button>
...

0
投票

尝试使用 fixedCacheKey 进行突变

© www.soinside.com 2019 - 2024. All rights reserved.