React功能使用过时的状态
我正在使用 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您应该以这种方式修改您的
usequery
部分I think that you should modify your
useQuery
section in this way