You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Query中queryClient.getQueryData()返回undefined的问题求助

React Query中queryClient.getQueryData()返回undefined的问题求助

我现在开发一个轶事应用,表单组件负责提交新内容到服务器,提交功能用React Query的useMutation已经正常工作了,但在onSuccess回调里用queryClient.getQueryData("anecdotes")想获取当前的查询数据来手动更新时,却一直返回undefined,导致没法用concat添加新的轶事,实在摸不着头脑🥲

下面是我的相关代码:

1. AnecdoteForm组件

import { createAnecdote } from "../requests";
import { useMutation, useQueryClient } from "react-query";

const AnecdoteForm = () => {
  const queryClient = useQueryClient();

  const newAnecMutation = useMutation(createAnecdote, {
    onSuccess: (newAnecdote) => {
      const anecdotes = queryClient.getQueryData("anecdotes");
      console.log(anecdotes); // 这里打印undefined
      queryClient.setQueryData("anecdotes", anecdotes.concat(newAnecdote));
    },
  });

  const onCreate = async (event) => {
    event.preventDefault();
    const content = event.target.anecdote.value;
    event.target.anecdote.value = "";
    newAnecMutation.mutate({ content, votes: 0 });
  };

  return (
    <div>
      <h3>create new</h3>
      <form onSubmit={onCreate}>
        <input name="anecdote" />
        <button type="submit">create</button>
      </form>
    </div>
  );
};

export default AnecdoteForm;

2. index.js入口文件

import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider } from "react-query";
import App from "./App";

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById("root")).render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

3. App组件

import AnecdoteForm from "./components/AnecdoteForm";
import Notification from "./components/Notification";
import { useQuery } from "react-query";
import { getAnecdotes } from "./requests";

const App = () => {
  const handleVote = (anecdote) => {
    console.log("vote");
  };

  const result = useQuery("notes", getAnecdotes, {
    refetchOnWindowFocus: false,
  });

  if (result.isLoading) {
    return <div>loading data...</div>;
  } else if (result.isError) {
    return (
      <div>anecdote service not available due to problems in the server</div>
    );
  }

  const anecdotes = result.data;

  return (
    <div>
      <h3>Anecdote app</h3>
      <Notification />
      <AnecdoteForm />
      {anecdotes.map((anecdote) => (
        <div key={anecdote.id}>
          <div>{anecdote.content}</div>
          <div>
            has {anecdote.votes}
            <button onClick={() => handleVote(anecdote)}>vote</button>
          </div>
        </div>
      ))}
    </div>
  );
};

export default App;

我预期从服务器获取的数据格式是这样的:

{
  "anecdotes": [
    {
      "content": "If it hurts, do it more often",
      "id": "47145",
      "votes": 0
    },
    {
      "content": "Adding manpower to a late software project makes it later!",
      "id": "21149",
      "votes": 0
    },
    {
      "content": "The first 90 percent of the code accounts for the first 90 percent of the development time...The remaining 10 percent of the code accounts for the other 90 percent of the development time.",
      "id": "69581",
      "votes": 0
    }
  ]
}

我检查了半天也没找到问题所在,有没有大佬能帮我看看为什么getQueryData("anecdotes")会返回undefined呀?

备注:内容来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.21 15:08:13