简体   繁体   English

React:组件在 state 更改后随机不刷新

[英]React: Component randomly doesn't refresh after state changes

I am working on a CRUD (express, mongoose, mongodb) which is mostly working as expected... except when it comes to rendering the entries after deleting X amount of them.我正在研究一个 CRUD(快递,mongoose,mongodb),它主要按预期工作......除了在删除 X 数量的条目后呈现条目。
Not deleting不删除

Sometimes I can delete 10 entries without any issues, until the component is empty, and other times I delete some entries and then the page just stop rending the updated data and enters an infinite loading state in the browser;有时我可以毫无问题地删除 10 个条目,直到组件为空,而其他时候我删除了一些条目,然后页面停止呈现更新的数据并在浏览器中进入无限加载 state; only when I hard reload the browser the page renders the latest data, yet it does delete the entry, it just freezes it seems!只有当我重新加载浏览器时,页面才会呈现最新数据,但它确实删除了条目,它似乎只是冻结了!

From React:
useEffect(() => {
    queryClient.invalidateQueries(["allUsers"]);
  });

const mutation = useMutation({
    mutationFn: async (userid) => {
      return await axios.delete("/api/deleteuser", { data: { userid: userid } });
    },
  });

 const handleDelete = (userid) => {
    mutation.mutate(userid);
    navigate("/", { replace: true });
  };
From Mongoose
const deleteUser = async (req, res) => {
  try {
    await newUser.findOneAndDelete({ userid: req.body.userid });
  } catch (error) {
    return error;
  }
};

Tried invalidating the query cache at the delete function but the result is the same.尝试在删除 function 时使查询缓存无效,但结果相同。 It just happens randomly, as if the request was not fulfilled... in dev tools.network the request is never fulfilled but the data, whenever it does work, is updated.它只是随机发生的,就好像请求没有被满足一样......在开发工具中。网络请求永远不会被满足但是数据,无论何时工作,都会被更新。 Network/pending网络/待定

Edit: I'm using a mongoDB free account... I've read sometimes the response times are not the best, perhaps it is the reason?编辑:我使用的是 mongoDB 免费帐户......我读过有时响应时间不是最好的,也许这是原因?

  1. useEffect without a dependency array is pretty pointless.没有依赖数组的useEffect是毫无意义的。 It will run every time the component is rerendered.每次重新渲染组件时它都会运行。
  2. I assume you are using react-query.我假设您正在使用反应查询。 Try moving your queryClient.invalidate to onSuccess or onSettled in your useMutation config object. This will ensure your query is invalidated only after the mutation is done.尝试将queryClient.invalidate移动到useMutation配置 object 中的onSuccessonSettled 。这将确保您的查询仅在突变完成后才失效。 https://react-query-v3.tanstack.com/guides/mutations#mutation-side-effects https://react-query-v3.tanstack.com/guides/mutations#mutation-side-effects

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM