React功能使用过时的状态

发布于 2025-01-26 11:26:27 字数 817 浏览 2 评论 0原文

我正在使用 react-query 根据当前状态获取外部数据,此处是代码的方式看起来

const Home = () => {
  const queryClient = useQueryClient();
  const [group, setGroup] = useState(1);

  const query = useQuery('/query', async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });

  useEffect(() => {
    queryClient.invalidateQueries('/query');
  }, [group, queryClient]);

  return (
    <div>
      <button onClick={() => setGroup(1)}>First group</button>
      <button onClick={() => setGroup(2)}>Second group</button>
    </div>
  );
};

有2个按钮可以更改状态(组),并且当状态更改(使用效果)时,我无效旧查询以发送新查询执行它打印出初始状态

I am using react-query to fetch external data, based on the current state here is how the code looks like

const Home = () => {
  const queryClient = useQueryClient();
  const [group, setGroup] = useState(1);

  const query = useQuery('/query', async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });

  useEffect(() => {
    queryClient.invalidateQueries('/query');
  }, [group, queryClient]);

  return (
    <div>
      <button onClick={() => setGroup(1)}>First group</button>
      <button onClick={() => setGroup(2)}>Second group</button>
    </div>
  );
};

There are 2 buttons that changes the state (group), and when the state changes (useEffect) I invalidate old queries to send new queries but the problem is that the callback has only the initial state and not the updated state and when it get executed it prints out the initial state

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

番薯 2025-02-02 11:26:27

我认为您应该以这种方式修改您的usequery部分

const query = useQuery(['/query', group], async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });

I think that you should modify your useQuery section in this way

const query = useQuery(['/query', group], async () => {
    console.log(group);

    return axios.get('/query', { params: { group } });
  });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文